我是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 ++还是很陌生,因此,如果对上面的代码进行一些细微的修改,那就太好了。谢谢!

最佳答案

您可以按以下方式读取文件:

int ix = 0;
int age = 0;
string name ="";
double height = 0.0;
ifstream inputFile.open(input.c_str()); //input is input file name

while (inputFile>> age >> name >>  height)
{
  PersonInfo p ={age, name, height};
  people[ix++] = p;
}

09-10 06:48
查看更多