问题
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