Reputation: 335
Suppose I have to take input of N
integers (previously provided by the user) and enter them into an array directly. For example
cin >> a >> b;
is given the input
5 10
5 is assigned to a and 10 to b.
I want a similar thing with arrays. Please help.
Upvotes: 3
Views: 3186
Reputation: 153919
If the list of integers is in a single line, and there is nothing else in that line:
std::vector<int>
getLineOfInts( std::istream& source )
{
std::string line;
std::getline( std::cin, line );
std::istringstream s( line );
std::vector<int> results;
int i;
while ( s >> i ) {
results.push_back( i );
}
if ( ! s.eof() ) {
// Syntax error in the line...
source.setstate( std::ios_base::failbit );
}
return results;
}
Upvotes: 4