If program wants an integer value, what if user enters string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

If program wants an integer value, what if user enters string

Idk could i explain my issue well, if i need to give you an example; i was making a tic tac toe game and I did this to control the input. //some codes ... int x,y, control = 0; while (control == 0) { cin>> x >> y; if ( //statement for checking if the place of table is empty and values are valid) else //display its not empty ... //some codes but this is not checking the if user enters string value or enters nothing Is my code right ? Should I do this with try except? if yes how?

19th Feb 2018, 10:37 AM
Mustafa K.
Mustafa K. - avatar
2 Answers
+ 2
You may use a try ... catch block and/or check for the failbit, if it has been set : Eg : #include<bits/stdc++.h> using namespace std; int main() { int a,b; // Variables to overwrite to. while(true) // Use an Infinite loop { cin>>a>>b; // Try to Read values for a and b. if(cin.fail()||cin.bad()) // If the input failed... cout<<"Wrong Input!\n"; else break; // We are done, go back. // Reset the Input Buffer conditions. cin.clear(); // Clears set bits. cin.ignore(numeric_limits<int> ::max()); // Remove \n's } cout<<a<<" "<<b; // Do other stuff. }
19th Feb 2018, 12:43 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 1
when u made the variable, you put int. if user inputs a string, it would cause a conversion exception and crash the program. so instead, make another string variable and check if it contains a number, then assign the int variable rhe value of the string variable
19th Feb 2018, 12:19 PM
Dominique Abou Samah
Dominique Abou Samah - avatar