c++ - 从文件中读取和存储数据时,每隔一行数据都会被跳过

标签 c++ file lines getline

我是 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/

相关文章:

c++ - Eclipse 中的 Irrlicht,环境不工作

c++ - 顶点着色器输入顺序

C - 从文本文件打印特定行

java-如何计算段落之间的空格并从总行数中减去它们?

c++ - 为什么这个 C 代码比这个 C++ 代码快?获取文件中的最大行

c++ - 位集和有符号值

python - 通过在 OPENCV 和实时视频中使用固有矩阵和畸变系数来进行相机校准

file - 如何在 Gradle 自定义任务中初始化 FileTree 字段?

C# resx 文件错误

algorithm - 将点捕捉到最近的线