如何解决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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。