无法找到输入文件
Cannot find input file
我正在尝试创建一个程序,该程序向用户询问文件的名称,然后打开该文件,将文件中列出的所有整数的总和相加,然后将该总和写入输出文件。
在写完我的代码并将testfile1.txt
保存到与程序相同的文件夹后,程序一直给我:"无法访问testfile1
"(我输出的消息通知我自己无法打开testfile1.txt
)。
这是我到目前为止所做的(跳过带有描述块的行):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream inputFile;
ofstream outputFile;
string testfile1;
string sum;
int total = 0;
int num;
cout << "Please input name of file." << endl;
cin >> testfile1;
cin.get();
inputFile.open(testfile1.c_str());
if (inputFile.fail()) {
inputFile.clear();
cout << "could not access testfile1" << endl;
return(1);
}
while (!inputFile.eof()) {
inputFile >> num;
total = total + num;
inputFile.close();
}
outputFile.open(sum.c_str());
outputFile << total << endl;
outputFile.close();
if (outputFile.fail()) {
cout << "could not access file." << endl;
return 1;
}
return 0;
}
问题:
我怎样才能使这个程序找到并打开testfile1.txt
?
注意:
我很确定,当提示输入文件名时,我没有拼错。
这里有一些备注可以帮助你找出可能的问题:
1。您可以通过在定义期间将流附加到文件中来减少一些代码行,而不是定义它们然后使用open
,如下所示:
ifstream inputFile(testfile1.c_str());
2。检查文件是否打开(如果不能打开则处理):
if (!inputFile) error ("Can't open input file: ", testfile1);
:
if (!outputFile) error ("Can't open output file: ", sum);
在定义后。
3。所有打开的文件都会在程序(或包含它们的函数)结束时隐式关闭,因此不需要显式地将它们close()
。
4。读取输入文件的内容并将它们相加:
int sum = 0;
string line;
// read a line
while (getline(inputFile, line)) {
stringstream ss(line);
// assuming you are reading integers separated by white space
int num = 0;
// extract each number on the line
while (ss >> num) total += num;
// reset line
line.erase();
}
注意:根据你的具体需要测试和修改你的代码。旁注:您可以在代码中省略:cin.get();
。
使用getline (std::cin,name);
输入名称并使用ostream的适当功能进行读写。
第21行和第22行
相关文章:
- 用c++从输入文件中读取另一行
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 获取通过重定向传入的输入文件的名称?
- C++ 如何打开带有另一个目录的输入文件?
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 如何从输入文件 c++ 创建随机名称生成器
- 从输入文件修剪空格
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 我遇到使用 c++ 逐行读取输入文件的问题
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 使用 getline 从输入文件打印时如何忽略空白行
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 数组大小由输入文件中的行数定义
- 从C++输入文件读取
- 在课堂上创建了一个朋友,给出"无输入文件"错误
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 利用输入文件中的数据(字符串和int)并在循环中利用
- C++ 仅读取输入文件中的部分(不是全部)数据以添加到记录中
- 如何从输入文件中读取字符并将其存储到向量中?