在 C++ 中,为什么 ifstream getline 在我的 .txt 文件中每隔一个数字返回一次,而不是返回所有数字?
In C++ why is ifstream getline returning every other number in my .txt file, rather than all of them?
当我 运行 此代码时,它不会打印 .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
header 中调用它
- 然后你在循环中调用它。
一次调用(while
header中的一次)就足够了,因为结果保存在line
变量中,循环body是免费的检查。
删除第二次调用将解决问题。
正如@dasblinkenlight 所指出的,您调用了 std::getline()
两次,这就是您看到的问题。
您看不到的问题是您正在将数据写入 Points[100]
,这是数组边界之外的无效位置。数组中的 100 个有效位置是索引 0 到 99,即 Points[0]
、Points[1]
、...、Points[99]
(因为 C++ 中的计数从 0 开始,而不是 1)。
写入 Points[100]
是 Undefined Behavior,这意味着您的程序可能会崩溃,或者更糟:在损坏自己的数据时可能不会崩溃。
由于您使用的是 C++,因此您可以随意使用 std::vector
and other containers,您可以在其中轻松存储您阅读的数字:
#include <vector>
// ...
vector<int> points;
while (getline(myfile, line))
{
int temp;
stringstream(line) >> temp;
points.push_back(temp);
cout << temp << endl;
}
当我 运行 此代码时,它不会打印 .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
header 中调用它
- 然后你在循环中调用它。
一次调用(while
header中的一次)就足够了,因为结果保存在line
变量中,循环body是免费的检查。
删除第二次调用将解决问题。
正如@dasblinkenlight 所指出的,您调用了 std::getline()
两次,这就是您看到的问题。
您看不到的问题是您正在将数据写入 Points[100]
,这是数组边界之外的无效位置。数组中的 100 个有效位置是索引 0 到 99,即 Points[0]
、Points[1]
、...、Points[99]
(因为 C++ 中的计数从 0 开始,而不是 1)。
写入 Points[100]
是 Undefined Behavior,这意味着您的程序可能会崩溃,或者更糟:在损坏自己的数据时可能不会崩溃。
由于您使用的是 C++,因此您可以随意使用 std::vector
and other containers,您可以在其中轻松存储您阅读的数字:
#include <vector>
// ...
vector<int> points;
while (getline(myfile, line))
{
int temp;
stringstream(line) >> temp;
points.push_back(temp);
cout << temp << endl;
}