How to fix infinite loop when user enters char into int data type | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to fix infinite loop when user enters char into int data type

When we tell a user to enter a number, but instead they enter a character/string, the program will try and convert it into a number. When I try to loop it so the user can re-input the variable, infinite loop occurs. How do I fix this

17th Jun 2017, 1:06 PM
Shawn Kou
Shawn Kou - avatar
6 Answers
+ 8
The keyword for these stuff is 'Input validation'. This code by @Ace is a great example of how to catch errors in such issues. https://code.sololearn.com/cUx55EsTKnaz/?ref=app A simple example using conditional statements would be: int num; cin >> num; if (cin.fail()) { cin.clear(); cin.ignore(512, '\n'); cout << "Not a number"; } wherein clear() clears the input buffer and ignore() extracts characters from the input sequence and discards them.
17th Jun 2017, 3:13 PM
Hatsy Rei
Hatsy Rei - avatar
+ 3
in while: cout<<...(Skip by the way) iNum = -1; cin >> iNum Sometimes Your code is infinite Idk the reason....
17th Jun 2017, 2:09 PM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 2
When the user enters bad input an error flag is set, its your job to clear this flag before accepting new input. cin.clear() is used to clear this flag. However, you still have to remove character(s) out of the stream. When cin is called again it will read the next character causing an error again, so you will also have to clear this by calling cin.ignore(Number of characters to clear, delimiter); The way I usually take user input is like this: int num; while(std::cout << "Enter a number: " && !(std::cin >> num)) //Note the parentheses are required here { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } std::numeric_limits<std::streamsize>::max() is used to make sure every character is deleted, you can enter your own number like 10000, but that would still cause errors if you have a user who enters characters beyond that. Note that you may have to include <limits> for that to work.
17th Jun 2017, 3:04 PM
Dennis
Dennis - avatar
+ 1
To begin with, could you show me a example you have?
17th Jun 2017, 1:09 PM
Judy
Judy - avatar
0
#include <iostream> using namespace std; int main(int argc, char** argv) { int iNum; cout<<"Please enter a positive number: "; cin>>iNum; while(iNum<=0) { cout<<"Please re-enter the number: "; cin>>iNum; } cout<<"Thanks"; return 0; }
17th Jun 2017, 1:15 PM
Shawn Kou
Shawn Kou - avatar
0
what if the user enters something like "9k"?
18th Jun 2017, 4:03 AM
Shawn Kou
Shawn Kou - avatar