Validating c input
This post discusses some of the techniques and its shortcomings and what could be done to improve the quality of validation.
Now, consider a program has to accept only integer inputs and reject all the others.
For #2, you can just do to discard as many characters in the input stream as possible until it reaches a newline character (from the user pressing Enter).
Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
So, the developer would have declared to store the integer value in say “int a;”. When the user input is accepted using the “cin I am a data science engineer and I love working on machine learning problems. I love writing and sharing my knowledge with others. Here I write about Python, Machine Learning, and Raspberry Pi the most.
I also write about technology in general, books and topics related to science.
My question is: What is the best way to validate input so it doesn't crash the program??? For example, if I enter "ffff", it will output: "Enter choice: Enter choice: Enter choice: Enter choice: " If I enter "fff" it will show "Enter choice: " three times. That is because cin is trying to read the f's one character at a time, because only one letter fits into char.
I don't know if this is the best solution, but you could make choice a string instead and use getline for input.
For single characters, you have two options: 1) If the user inputs more than one character, reject the input and prompt the user for a new input, or 2) Just take the first character the user inputs and discard whatever else the user might have entered after that (if anything).
The reason behind this is when you hit return\enter on your keyboard, a newline character is passed in as input.
These extra hidden characters are what is messing with your input and spawning the infinite while loop.
To troubleshoot more easily I copied my code from task 1 and 2 into Visual Studio, so I could preview the console application there.
After making changes the code seems to be doing what it should... There is nothing technically wrong with your code, you are very thorough and the program is well designed, if this was a challenge issued by and evaluated by a human it would likely pass.