尝试编写一个程序,该程序在文本文件中产生所有以空格分隔的整数的和

问题描述

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

#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";
}

我正在读取的文件

words 32 jd: 5 alkj 3 12 fjkl 
23 / 32
hey 332 2 jk 23 k 23 ksdl 3
32 kjd 3 klj 332 c 32

解决方法

在使用ReferenceString之前,您没有正确读取整数,或者没有正确检查operator>>是否成功。而且更重要的是,number遇到非整数输入时,您不会清除流的错误状态。

尝试更多类似方法:

operator>>

Live Demo

,

看看是否可行:

  function writeTheData(tempData) {
    return $.ajax({
      url: "http://localhost:7000/api/writeJSONtoInfluxDB",type: "POST",contentType: "application/json",data: tempData,success: function (data) {
        console.warn("uploading and import data: " + data);
      },}).then((response) => response.data);
  }