我是C++的新手,从文本文件读取数据行时遇到了一些麻烦。假设我在文本文件中有未知数的行,每行的格式都是相同的:int string double。唯一可以确定的是空间将分隔给定行上的每一条数据。我正在使用结构数组来存储数据。下面的代码很好,除了在每个循环之后跳过一行输入。我试过插入各种ignore()语句,但仍然无法读取每行,只读其他行。如果我在最后重写了一些getline语句,那么在第一次循环之后,将开始为变量存储错误的数据。当读取和存储文件中的数据时,其他每行数据都会被跳过
文本文件可能是这样的:
18 JIMMY 71.5
32 TOM 68.25
27 SARAH 61.4
//code
struct PersonInfo
{
int age;
string name;
double height;
};
//..... fstream inputFile; string input;
PersonInfo *people;
people = new PersonInfo[50];
int ix = 0;
getline(inputFile, input, ' ');
while(inputFile)
{
people[ix].age = atoi(input.c_str());
getline(inputFile, input, ' ');
people[ix].name = input;
getline(inputFile, input, ' ');
people[ix].height = atof(input.c_str());
ix++;
getline(inputFile, input, '\n');
getline(inputFile, input, ' ');
}
我敢肯定有更先进的方法可以做到这一点,但就像我说的,我很新的C++所以如果有只是稍作修改到上面的代码,那会很棒。谢谢!
我读到了全线然后解析行成翘楚领域。 – John3136 2013-04-11 02:12:56