JamsoWamso
JamsoWamso

Reputation: 51

How can I take multiple ints on one line with C++, without knowing how many will be inputed?

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.

Upvotes: 4

Views: 7150

Answers (3)

Peter B
Peter B

Reputation: 416

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();

Upvotes: 5

Incomputable
Incomputable

Reputation: 2208

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.

Upvotes: 1

Nishant
Nishant

Reputation: 1665

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.

Upvotes: 0

Related Questions