【问题标题】:ifstream usage and user input not outputting content to readifstream 使用和用户输入不输出要读取的内容
【发布时间】:2021-02-17 15:31:51
【问题描述】:

我正在练习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");
}

【问题讨论】:

  • while(num &gt; 0); -> while(inputFile); ?
  • 您的循环将在num &lt;= 0 时结束。您的意思是在阅读完所有 inputFile 后停止吗?
  • @scohe001 是的,我希望它在阅读完所有内容后停止。
  • @scohe001 当我这样做时 while(inputFile);它读取最后一个数字两次,有什么帮助吗?
  • 练习时请记住,当您的代码查看返回码时,调试起来要容易得多。在流的情况下,返回码是流本身。你几乎不应该stream &gt;&gt; some_var;。相反,您应该拥有类似于if (stream &gt;&gt; some_var) { use some_var} else { report error and clean up the mess } 的东西。特别是当流由用户控制时。用户是渣滓。有很多用户为了乐趣和利润而破坏您的程序,其余的都是白痴,大部分时间都无法按下正确的键。

标签: c++ while-loop do-while ifstream


【解决方案1】:

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

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

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

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

        if (inputFile.is_open()) {
            int num = 0;
            int total = 0;
            while (inputFile >> num) {
                total += num; 
            }
            inputFile.close();
            cout << "Total is: " << total << endl;
        }
        else {
            cout << "Failed to open file." << endl;
        }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多