在c++中,为什么ifstream getline返回我的.txt文件中的每一个数字,而不是所有的数字

In C++ why is ifstream getline returning every other number in my .txt file, rather than all of them?

本文关键字:数字 每一个 txt ifstream 为什么 c++ getline 返回 我的 文件      更新时间:2023-10-16

当我运行这段代码时,它不打印。txt文件的内容,即数字1到100,它打印所有到100的偶数(例如2 4 6 8等等)。我不知道为什么,以前没有,我不认为我改变了什么。我用的是xcode。有人有什么想法吗?

#include <stdio.h>     
#include <iostream>     
#include <cmath>        
#include <string>       
#include <sstream>      
#include <fstream>

using namespace std;
int main () {
    string line;
    int Points[100];
    ifstream myfile("StatNum.txt");
    if (myfile.is_open())
    {
        while ( getline (myfile,line) )
        {
            getline(myfile,line);
            stringstream(line) >> Points[100];  //uses stringstream to convert Myline (which is a string) into a number and put it into an index of Points
            cout << Points[100] << endl;
        }
        myfile.close();
    }
    else cout << "Unable to open file" << endl;
    return 0;
}

这是因为每次迭代调用getline两次:

  • 首先,在while头文件
  • 中调用它
  • 然后在循环中调用。

一次调用(while头中的调用)就足够了,因为结果保存在line变量中,循环体可以自由地检查该变量。

删除第二次调用将解决这个问题。

正如@dasblinkenlight指出的那样,您调用std::getline()两次,这就是您看到的问题。

您看不到的问题是,您正在将数据写入Points[100],这是一个无效的位置,超出了数组的边界。数组中的100个有效位置是索引0到99,即Points[0], Points[1],…, Points[99](因为c++从0开始计数,而不是1)。

写入Points[100]是未定义的行为,这意味着你的程序可能会崩溃,或者更糟的是:可能不会在损坏自己的数据时崩溃。

因为你使用的是c++,所以你可以使用std::vector和其他容器,在那里你可以很容易地存储你读到的数字:

#include <vector>
// ...
vector<int> points;
while (getline(myfile, line))
{
    int temp;
    stringstream(line) >> temp;
    points.push_back(temp);
    cout << temp << endl;
}
相关文章: