c ++ чтение данных из входного файла в 3 параллельных массива в зависимости от типа данных

Возникли проблемы при сортировке данных во входном файле в указанный массив. Входной файл содержит строку, double и int.

  • TN 54,5 7
  • KY 65,6 23
  • PA 123,3 30
  • и т.п.

Существует 14 строк типа string, double, int типов данных. Данные должны быть напечатаны на экране в том же формате, что и файл. Мне удалось распечатать данные на экране, используя один «строковый массив», но данные не распечатываются в порядке, указанном выше. Я пытался использовать getline (), и в ходе исследований многие говорили об использовании просто «input >> variable [max];» для каждой отдельной переменной. Это только печатает огромное количество и число 53, ни один из которых содержится во входном файле. Я чувствую, что делаю это сложнее, чем есть. Я знаю, что мой массив слишком мал, чтобы прочитать количество необходимых данных (которые я планирую исправить). Не просить кого-то, чтобы выяснить это для меня. Просто нужно указывать в правильном направлении. Есть ли более простой способ сортировки данных в нужный массив?

Код ниже — это то, что я использовал с одним массивом для чтения всех типов данных.

#include <iostream>
#include <fstream>

using namespace std;

void readData(ifstream& input, string []);
int main()
{
string data[14];
char filename[256];
fstream input;

cout << "Enter file name: ";
cint >> filename;

input.open(filename);
if (input.fail())
{
cout << "opening file fail." << endl;
}

readData(input, data);

input.close();
return(0);
}

void readData(ifstream& input, string data[14])
{
int count;

count = 0;
while (count < 14 && !input.eof())
{
input >> data[count];
count << data[count] << endl;
count++;
}
}

0

Решение

почему не один цикл? (видеть это живи здесь)

#include <iostream>
#include <sstream>
#include <vector>

void read_data(std::istream& input, std::vector<std::string>& strings, std::vector<double>& doubles, std::vector<int>& ints) {
std::string s; double d; int i;
while( input >> s >> d >> i ) {
strings.push_back(s);
doubles.push_back(d);
ints.push_back(i);
}
}

int main() {
std::istringstream i { "FN 3.2 22\nBB 3.48 48\nXX 2.03 172\n" };
std::vector<std::string> strings;
std::vector<double> doubles;
std::vector<int> ints;

read_data(i, strings, doubles, ints);
std::cout << "strings:\n";
for(auto s: strings) std::cout << "  " << s << "\n";
std::cout << "doubles:\n";
for(auto d: doubles) std::cout << "  " << d << "\n";
std::cout << "ints:\n";
for(auto i: ints) std::cout << "  " << i << "\n";
}
1

Другие решения

ifile.open(filename);

if (ifile.is_open()){int indexValue = -1;

while ( ifile.getline(buffer, 100) ){indexValue++;
counter = 0;token = strtok(buffer, " ");

while (token){if(counter == 0){

strcpy(stringArray[indexValue],token);
cout<< "string " <<stringArray[indexValue] << endl;

}

counter++;

stringstream ss;
int value =0;
if(counter == 1){
token = strtok(NULL, " ");
ss << token;
ss >> value;
intArray[indexValue] = value;
cout << "int " << intArray[indexValue] << endl;

}
}

counter++;

stringstream ss;
double value1 =0.0;
if(counter == 2){
token = strtok(NULL, " ");
ss << token;
ss >> value;
doubleArray[indexValue] = value1;
cout << "Score " << doubleArray[indexValue] << endl;

}
token = strtok(NULL, " ");
counter = 0;
}
}
0

По вопросам рекламы [email protected]