Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

cin

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?

like image 572
user2514676 Avatar asked Apr 14 '26 04:04

user2514676


2 Answers

What about

vector<int> intVector( std::istream_iterator<int>( std::cin ), 
                       std::istream_iterator<int>() );
like image 60
sbabbi Avatar answered Apr 16 '26 20:04

sbabbi


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;
}
like image 27
Alfred Huang Avatar answered Apr 16 '26 22:04

Alfred Huang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!