Sigh. What I get for not compiling my own code first.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector <int> data1;
while (true)
{
// I forgot this: make sure you start with a clean vector
data1.clear();
// Tell the user what you want:
cout << "Enter a list of integer numbers: ";
// Get the entire line at once
string s;
getline( cin, s );
// Break the line up into individual int values using the >> operator
istringstream ss( s );
int n;
while (ss >> n)
data1.push_back( n );
// Did we reach the end of the line (string) without any errors?
if (ss.eof())
// Yes! Great! We're done!
break;
else
// Fooey! Tell the user to try again...
cerr << "Hey, element " << (data1.size() + 1) << " is not an integer number!\n";
}
// Reward the user for doing it right.
cout << "Good job! You entered:\n";
for (unsigned n = 0; n < data1.size(); n++)
cout << data1[ n ] << endl;
cout << "Bye!\n";
return 0;
}
|
Try it and see what you can do to make it fail.
Line 29 explicitly tests to see if the
stringstream terminated because of EOF and not some other error condition -- any other error condition will do. EOF is only signalled if the line parsed properly and completely into integer values.
Given this context, the only possible error that you can have is 'bad input': not an integer. The error message speaks precicely to that error, and even tells you where you went wrong.
(Though it could be off by one if you input something like
1 2.7 9
or
1 42rules! -3
, a possibility I did not consider when typing this off the top of my head. As always, test code before you are done with it, so if this is an issue you can put in tests for separation between an error value and any previous element.)
Why would >> fail with spaces? It never does elsewhere (unless you explicitly use
noskipws to tell it otherwise).
The nice feature about code like this is that it doesn't require all the flags and tests and other malarky necessary to deal with some oddball "marker"/"signal"/"semaphore" value. Instead it uses the marker value already given to us: the End Of Line (or "newline"). It decodes as many integers as it can out of a single line of text. When the line is exhausted, you have your complete list -- as many or as few elements as the user specified (including zero).
Hope this helps.