gpt4 book ai didi

c++ - 为什么当 ifstream 使用从键盘读取的字符串创建文件时出现错误?

转载 作者:行者123 更新时间:2023-11-30 02:15:04 25 4
gpt4 key购买 nike

我正在做 Bjarne Stroustrup 的书 Programming Principles and Practice Using 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 创建。

最佳答案

[...] in the same directory with main.cpp [...]

输入文件相对于源文件的位置并不重要。运行程序时,该文件应位于环境的当前工作目录中。

关于c++ - 为什么当 ifstream 使用从键盘读取的字符串创建文件时出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56667482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com