简体   繁体   English

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

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

When I run this code it doesn't print the contents of the .txt file which is numbers 1 to 100, it prints all of the even numbers up to 100 (eg 2 4 6 8 so on.) And I don't know why, it didn't before and I don't think I changed anything.当我运行此代码时,它不会打印 .txt 文件的内容,即数字 1 到 100,它会打印所有偶数到 100(例如 2 4 6 8 等)。我不知道为什么,以前没有,我认为我没有改变任何东西。 I'm using xcode.我正在使用 xcode。 Anybody got any ideas?有人有任何想法吗?

#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;
}

This happens because you call getline twice per iteration:发生这种情况是因为每次迭代调用getline两次:

  • First, you call it in the while header首先,您在while标头中调用它
  • Then you call it inside the loop.然后在循环内调用它。

One invocation (the one in the while header) is sufficient, because the result is saved in the line variable, which the loop body is free to examine.一次调用( while头中的那个)就足够了,因为结果保存line变量中,循环体可以自由检查该变量。

Removing the second invocation will fix the problem.删除第二个调用将解决问题。

As @dasblinkenlight pointed out, you are calling std::getline() twice and that's the problem that you see.正如@dasblinkenlight 指出的那样,您两次调用std::getline() ,这就是您看到的问题。

The problem that you can't see is that you are writing data to Points[100] which is an invalid location, outside of the array's bounds.您看不到的问题是您正在将数据写入Points[100] ,这是数组边界之外的无效位置。 The 100 valid locations in your array are indexes 0 to 99, that is Points[0] , Points[1] , ..., Points[99] (because counting in C++ starts from 0, not 1).数组中的 100 个有效位置是索引 0 到 99,即Points[0] , Points[1] , ..., Points[99] (因为 C++ 中的计数从 0 开始,而不是 1)。

Writing to Points[100] is Undefined Behavior which means that your program may crash, or worse: may not crash while corrupting its own data.写入Points[100]未定义的行为,这意味着您的程序可能会崩溃,或者更糟:在破坏自己的数据时可能不会崩溃。

Since you're using C++ you have std::vector and other containers at your disposal, where you can easily store the numbers you read:由于您使用的是 C++,因此您可以使用std::vector和其他容器,您可以在其中轻松存储读取的数字:

#include <vector>

// ...

vector<int> points;

while (getline(myfile, line))
{
    int temp;

    stringstream(line) >> temp;
    points.push_back(temp);
    cout << temp << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM