在文件中查找整数总和并将其放入另一个文件?还是错误的输出?

时间:2018-11-18 19:52:58

标签: c++ file loops for-loop

我正在尝试在一个文件中查找总和并将其输出到另一个文件,但是当我打开输出文件时总和仍为0?

include <fstream>
using namespace  std;
void main() {
    ifstream fin("inFile.txt");  // create input stream & connects to file
    ofstream fout("outFile.txt");  // create output stream & connects to file

    int n = 0, sum = 0, num = 0;
    fin >> n;        // read the number of integers from inFile.txt
    for (int i = 0; i < n; i++) {
        fin >> num;
        sum = sum + num;
    }
    fout << "sum is " << sum << endl;
    fin.close();
    fout.close();
}

1 个答案:

答案 0 :(得分:3)

文件的基本结构没有多大错误,但在很大程度上也取决于输入文件格式。考虑到读取输入很容易出错,应该在输入流上添加多次检查以检查失败。

所以要么在调试器下运行程序,要么添加适当的打印语句。

#include <cstdlib>
#include <fstream>

int main() {
    std::ifstream fin("inFile.txt");  // create input stream & connects to file
    if (!fin) return EXIT_FAILURE;
    std::ofstream fout("outFile.txt");  // create output stream & connects to file
    if (!fout) return EXIT_FAILURE;

    int n = 0, sum = 0, num = 0;
    fin >> n;        // read the number of integers from inFile.txt
    if (!fin) return EXIT_FAILURE;
    for (int i = 0; i < n; i++) {
        if (!fin >> num) return EXIT_FAILURE;
        sum = sum + num;
    }
    fout << "sum is " << sum << std::endl;
    return EXIT_SUCCESS;
}