4

I'm using cin >> x[0] >> x[1] >> x[2] >> x[3]; etc to get input such as:

1 2 3 4.

But my problem is that there could be anywhere from 3 different numbers (1, 2, and 3, for example) to 20 different numbers, and I won't know how many beforehand. Because the user could enter up to 20 numbers, I've repeated the pattern above until x[19]. I've found that the program will not continue until it has an input for every single one of these values.

KyleL
  • 855
  • 6
  • 24
JamsoWamso
  • 51
  • 1
  • 3
  • 2
    Naive solution: ask for the numbers to be entered first and then do a loop. Otherwise interpret some special value (either numeric or not) as a terminator. – Marco A. Aug 06 '15 at 08:42
  • You could try reading string from input and parse it. Split input string on space character and convert each sub string to int. – aisbaa Aug 06 '15 at 08:43

3 Answers3

5

Use std::getline to read a whole line, then create an std::istringstream, and read the int's in a while cycle. If parsing fails, std::ios_base::failbit will be set, that should be checked in the while condition (by implicitly casting the istringstream to bool). When all input is parsed successfully, the std::ios_base::eofbit will be set after leaving the cycle.

Something like this:

std::string line;
std::getline(std::cin, line);

std::istringstream input(line);
std::vector<int> result;
int value;
while (input >> value)
{
    result.push_back(value);
}
const bool success = input.eof();
Peter B
  • 416
  • 2
  • 7
  • 2
    And of the user is malicious and enters "Hi"? Then you'll get UB since value isn't initialised and you don't check for failure. In short, don't just check for eof, better use while (input >> value) { ... } to check the actual input operation – Daniel Jour Aug 06 '15 at 09:14
  • See also [here](http://stackoverflow.com/q/5431941/509868) about `feof`, which has the same problem (easy to use incorrectly; better not to use at all) – anatolyg Aug 06 '15 at 10:02
  • 1
    @DanielJour You are right, I updated the code with (more) appropriate error handling. – Peter B Aug 06 '15 at 13:05
1

cin returns true when variable is read, so you can use

while (cin>>x[ind++])

the question on while (cin >> ) check that for more information.

Community
  • 1
  • 1
Incomputable
  • 2,188
  • 1
  • 20
  • 40
0

Just give user an option: - to stop entering numbers press"Q", and place a check for it in your code. When user enters Q, go ahead with your code.

Or you can ask user to enter how many numbers he will be inserting.

Nishant
  • 1,635
  • 1
  • 11
  • 24