简体   繁体   中英

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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM