How to anticipate single or multiple input failure(s) when input(s) are read in using C++ std::cin and extraction operator >> | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

How to anticipate single or multiple input failure(s) when input(s) are read in using C++ std::cin and extraction operator >>

Hello SoloLearners, I'm asking this question because I need suggestions on how to anticipate input failure when reading in multiple data using chained extraction operator >> Let's see an example so we could stay on the same boat. Assume the snippet in main() function body, with necessary headers included. int n1, n2, n3; std::cin >> n1 >> n2 >> n3; How do I deal when: 1. User input nothing. 2. User input 3 values, but none of the values were valid subject for conversion to integer. 3. User input 1 or 2 valid integers, rest are no valid subject for conversion to integer. 4. User input only 1 valid integer, rest are no valid subject for conversion to integer. I'm curious, is it possible for me to know how many values are successfully read-in and converted to integers (C scanf() supports that). Also if possible, I would like to know which, amongst the 3 variables (n1, n2 and n3) has a valid data, so I wouldn't be using ones that contains invalid data. Thank you, in advance ...

27th Mar 2023, 6:25 AM
Ipang
2 Answers
+ 5
The most robust way in my opinion is to accept any kind of input from the user. That is, read the line as string. If the user enters nothing, he is going to sit at an input prompt. He might issue an EOL (it is ctrl+d, i believe), with getline i reckon you get an empty string. Once the input is read, you can go nuts doing all sorts of crazy tests. The more detailed you want the knowledge about the input, the more code you need. Use a stringstream on the input and extract one by one. I am sure you know about handling extraction failured from streams. Or split the string at whitespaces first and analyse each component in any order you like. But I do not see it possible to do it in one go with a detailed problem analysis afterwards.
27th Mar 2023, 7:38 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 5
Ani Jona 🕊 Yes, you're absolutely right. Use of string input to be parsed manually later on is one robust way into this. I suppose there's just no easy way to get around input failures when using chained extraction operator to read values in for multiple variables. Guess it's a price to pay for the ease-of-use provided by the operator : )
27th Mar 2023, 10:38 AM
Ipang