c++ - 尝试编写一个程序来生成文本文件中所有空格分隔的整数的总和
问题描述
我没有收到任何错误,只是一个无限循环!这是我的代码:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<fstream>
#include<assert.h>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
int sum{ 0 }, number;
vector<int> numbers;
string word;
fstream file;
file.open("file1.txt", fstream::in);
while (true) {
file >> number;
if (file.eof()) {
numbers.push_back(number);
break;
}
else if (file.fail()) { file >> word; }
else if (file.bad()) exit(1);
else numbers.push_back(number);
}
for (int x : numbers) sum += x;
cout << sum << "\n";
}
我正在阅读的文件:
单词 32 jd: 5 alkj 3 12 fjkl 23 / 32 嘿 332 2 jk 23 k 23 ksdl 3 32 kjd 3 klj 332 c 32
解决方案
您没有正确读取整数,或者operator>>
在使用之前正确检查是否成功number
。更重要的是,当遇到非整数输入时,您不会清除流的错误状态operator>>
。
尝试更多类似的东西:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <stdexcept>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
int sum = 0, number;
vector<int> numbers;
string word;
ifstream file("file1.txt");
while (file >> word) {
try {
number = stoi(word);
}
catch (const std::exception &) {
continue;
}
numbers.push_back(number);
}
if (file.fail() && !file.eof())
exit(1);
for (int x : numbers)
sum += x;
cout << sum << "\n";
keep_window_open();
return 0;
}
推荐阅读
- c - 执行 cpp-driver datastax 时出现协议错误
- db2 - 我正在寻找使用 php 在 DB2 上运行 sql 查询的驱动程序 (linux) 可以建议如何执行此操作吗?
- android - 从Android的BottomSheet Fragment中的导航栏中删除间隙/边距
- python - 单击kivy按钮时如何调用函数?
- ruby-on-rails - Dockerized nmap 显示不正确的操作系统版本
- python - 基于 DateTime 列合并两个熊猫数据框
- html - 试图改变甚至列表链接css?
- typescript - 如何使用打字稿设置自定义 node_modules 路径
- javascript - Leaflet.js gdpr 兼容集成
- python - 如何限制我的图表在 matplotlib 中低于零