在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
头文件 中调用它 - 然后在循环中调用。
一次调用(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;
}
相关文章:
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 对于C++中的每一个都无法更新向量
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 如何从这些语句中的每一个创建不同的函数?
- 在C++中,系统如何将这些对象中的每一个与执行程序的窗口相关联?
- 如何将字符串和数字放在一个多维数组中?
- 如何为字符串编写正则表达式,其中包含一个数字至少一个数字,并且不包含任何字母
- 从一串数字C++创建一个数字序列
- 我怎样才能将像 123 这样的数字变成一个带有 ascii 的字符串C++
- 在整数C 中分开每一个数字
- 找不到正确的 Qt5Core.dll 文件。我发现的每一个都会给出不同的错误
- 将一个数字的一个数字与其当前位置相乘,然后使用递归将其和其他数字相加
- 为什么这段代码会给我的数字加一个额外的零
- C++-是否可以使用random_shuffle生成数组的每一个排列,一次且仅一次
- 在一行代码中输入2个十六进制数字和一个字符串
- 为什么我的struct只存储最后一个字符串,而不是每一个
- 从输入中获取一个数字和一个单位作为双精度和字符串——编程:使用c++的原则和实践
- 如何添加一个数字到一个字符串
- 在c++中,为什么ifstream getline返回我的.txt文件中的每一个数字,而不是所有的数字
- 给定了在C++中返回对象的各种方法,这些返回语句中的每一个都有哪些潜在的问题