【发布时间】:2014-06-09 19:56:16
【问题描述】:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> temp;
ifstream infile;
infile.open("numbers");
if (infile.fail())
{
cout << "Could not open file numbers." << "\n";
return 1;
}
int data;
infile >> data;
while (!infile.eof()) {
temp.push_back(data);
infile >> data;
}
cout << data << " " << endl;
}
我只是想使用向量从文本文件“数字”中找出所有数字。
15
10
32
24
50
60
25
我的经验几乎为零,关于为什么无法打开的一些指导会非常有帮助。
【问题讨论】:
-
data在您打印时不在范围内。还有while (!eof())is wrong.. -
不是我推荐使用
eof,而是按照这个顺序完成,只要不复制最后一个值就可以了。当然,任何其他错误都将被忽略。data在打印时看起来也在我的范围内,但在循环之外它只会打印最后一个值。 -
阅读问题的最后一行和您的其他一些 cmets,您能否澄清您实际遇到的问题?听起来您一开始就无法打开文件。它与可执行文件位于同一目录中吗?你是在 ide 里面运行这个吗?如果是这样,您可能需要将工作目录设置为 numbers 文件所在的位置,以便您的程序找到它。