ifstream用法和用户输入未输出要读取的内容

问题描述

我正在练习ifstream用法。我希望用户输入要读取的文件,在此示例中为 num1.txt 。我希望控制台从num1.txt中读取一个字母,然后将其单独输出

我已经运行了下面的代码,并将"num1.txt"输入到控制台后,我什么也没回来。我尝试将cout << num << endl;移到内部do语句,但最终以无限数量重复数字10

我在做什么错了?

num1.txt中的内容

2 4 6 8 10
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main() {
    string fileName,cont;
    ifstream inputFile;

    do {
        int num = 0;
        int total = 0;
        cout << "Please enter the file name: ";
        cin >> fileName;
        inputFile.open(fileName);

        if (inputFile.is_open()) {
            do {
                inputFile >> num;
                total += num; 
            }
            while(num > 0);

            if (total != 0) {
                cout << num << endl;
                cout << "Total is: " << total << endl;
            }
        }
        else {
            cout << "Failed to open file." << endl;
        }

        inputFile.close();
        cout << "Do you want to continue processing files? (yes or no): " << endl;
        cin >> cont;
    }
    while (cont == "yes");
}

解决方法

在使用collectstatic --clear之前,您的内部do循环未正确验证operator>>实际上是否成功。每次读取后,它应该查看流的错误状态。最简单的方法是将num循环更改为do循环,该循环将读取结果用作循环条件,例如:

while