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