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

13,054

Solution 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;
}

Solution 2

What about

vector<int> intVector( std::istream_iterator<int>( std::cin ), 
                       std::istream_iterator<int>() );
Share:
13,054
user2514676
Author by

user2514676

Updated on June 05, 2022

Comments

  • user2514676
    user2514676 almost 2 years

    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?

  • BugShotGG
    BugShotGG about 8 years
    nice one! Dont forget to include <iterator> header.
  • jww
    jww over 5 years
    Does this meet specifications? What happens with an input of 1 2\n3 4\n. It seems like both lines will be processed instead of the first line.