我正在Bjarne Stroustrup的书《使用C++编程原理和实践》中进行练习。我正在第10章的第一个练习中,它说要编写一个程序,该程序在空格分隔的整数文件中产生所有数字的和。我下面的代码基于第10.5章的练习2中使用的代码。创建ifstream
对象时出现错误。这是我尝试运行的代码:
#include "../../std_lib_facilities.h"
int main(int argc, const char * argv[]) {
// insert code here...
cout << "Plese enter the input file name: " << endl;
string iname;
cin >> iname;
ifstream ist {iname};
if (!ist) error("Can't open input file ",iname);
vector<int> numbers;
int sum;
int n;
while(ist>>n) {
numbers.push_back(n);
}
for (int i=0; i<numbers.size(); ++i) {
sum += numbers[i];
}
cout << sum << endl;
return 0;
}
我输入的任何输入都出错。我尝试了myin,myin.txt或其他任何名称。
error("Can't open input file ",iname);
来自作者创建的库。我知道该文件确实与main.cpp存在于同一目录中,并使用纯文本格式从Mac使用TextEdit创建。
最佳答案
将输入文件放在相对于源文件的位置并不重要。
运行该程序时,该文件应位于环境的当前工作目录中。
关于c++ - 当ifstream用键盘读取的字符串创建文件时,为什么会出现错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56667482/