无法找到输入文件

Cannot find input file

本文关键字:输入 文件      更新时间:2023-10-16

我正在尝试创建一个程序,该程序向用户询问文件的名称,然后打开该文件,将文件中列出的所有整数的总和相加,然后将该总和写入输出文件。

在写完我的代码并将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行