How can I avoid char input for int variable?

The program below shows the value "int", which is input and output at the same time. However, when I entered the character, it goes into an infinite loop displaying the previously entered "int" value. How can I avoid typing a character?

#include<iostream> using namespace std; int main(){ int n; while(n!=0){ cin>>n; cout<<n<<endl; } return 0; } 
+4
source share
3 answers

Reason for infinite loop:

cin goes into a failed state, and this causes it to ignore further calls until the error flag and buffer are reset.

 cin.clear(); cin.ignore(100, '\n'); //100 --> asks cin to discard 100 characters from the input stream. 

Check if the input is numeric:

In your code, even the non-int type is still added to the int. It is not possible to check whether the input is numeric without entering input into the char array and calling the isdigit() function for each digit.

The isdigit () function can be used to mark numbers and alphabets. This function is present in the <cctype> header.

The is_int () function will look like this.

 for(int i=0; char[i]!='\0';i++){ if(!isdigit(str[i])) return false; } return true; 
+8
source

If you want to use the user definition function, you can use the ascii / ansi value to limit char input.

48 -57 is a range of values ​​from 0 to 9

0
source
 #include <iostream> #include <climits> // for INT_MAX limits using namespace std; int main() { int num; cout << "Enter a number.\n"; cin >> num; // input validation while (cin.fail()) { cin.clear(); // clear input buffer to restore cin to a usable state cin.ignore(INT_MAX, '\n'); // ignore last input cout << "You can only enter numbers.\n"; cout << "Enter a number.\n"; cin >> num; } } 
0
source

All Articles