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?
What about
vector<int> intVector( std::istream_iterator<int>( std::cin ),
std::istream_iterator<int>() );
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With