我是 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;
}
关于c++ - 从文件中读取和存储数据时,每隔一行数据都会被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15939568/