cin directly to vector<int>, break loop when no more data

六月ゝ 毕业季﹏ 提交于 2019-12-22 12:34:07

问题


The following code runs and stores input in the vector as it should but loops indefinitely listening for input. The intent is to take a string of ints from one line of input, separated by spaces, and store them in a vector.

int main(int argc, char ** argv){
    int input;
    vector<int> intVector;
    while (cin >> input) 
        intVector.push_back(input);
    //print vector contents
    copy(intVector.begin(), intVector.end(), ostream_iterator<char>(cout, " ")); cout << "\n";

    return 0;
}

I want to somehow add a simple, extra condition in the while loop that checks for the end of the line so that it doesn't just keep listening indefinitely. cin.oef is no use here. I've tried that and several other things already.

Is there something clean, short, and elegant that I can add to fix this?


回答1:


You can use sstream lib:

#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <iterator>
using namespace std;

int main(int argc, char ** argv) {

    string buf;

    while(getline(cin, buf)) {

        istringstream ssin(buf);
        vector<int> intVector;
        int input;
        while(ssin >> input) {
            intVector.push_back(input);
        }

        //print vector contents
        cout << intVector.size() << endl;
        copy(intVector.begin(), intVector.end(), ostream_iterator<int>(cout, " "));
        cout << "\n";
    }

    return 0;
}



回答2:


What about

vector<int> intVector( std::istream_iterator<int>( std::cin ), 
                       std::istream_iterator<int>() );



回答3:


If you want to avoid errors, such as inserting a character into a integer variable, you could do:

while (some condition) {
  if (!(std::cin >> int_variable)) {
    std::cin.clear();
    std::cin.ignore(1024, '\n');
  } else {
    array.push_back(int_variable);
    // Anything else or increment the condition variable
  }
}


来源:https://stackoverflow.com/questions/24582852/cin-directly-to-vectorint-break-loop-when-no-more-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!