首页 > 解决方案 > 尝试编写一个程序来生成文本文件中所有空格分隔的整数的总和

问题描述

我没有收到任何错误,只是一个无限循环!这是我的代码:

#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

标签: c++fstream

解决方案


您没有正确读取整数,或者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;
}

现场演示


推荐阅读