+ 1
How do I check if user input is a number?
How do I check if user input is a number? EDIT: My brain failed at typing english so I corrected it i guess.
6 Réponses
+ 11
// not the usual try-catch statements, but built around that logic, and also captures invalid ranges.
#include <iostream>
#include <cstdlib>
#include <ctime>
int main ()
{
int x = 0; srand(time(0));
while (x < 1)
{
std::cin >> x;
if (std::cin.fail() || x < 1)
{
std::cin.clear(); std::cin.ignore(512, '\n');
x = 0;
std::cout << "Invalid input, please try again.";
}
}
std::cout << "Your random number is: " << 1 + (rand() % x) << std::endl;
return 0;
}
+ 3
Yes ! You can use something like that :
bool error = false;
do{
try{
cin>>x;
}catch(...){
error=true;
cout<<"Invalide input"<<endl;
}while(error);
+ 1
This was a C code I did a while back. If you want the code to break in a none numerical character, just throw an error (Cpp of course)
https://code.sololearn.com/cV5gNflArWDz/?ref=app
Another solution would be to do something like this
int n; //or double
bool error = false;
try{
cin>>n;
}catch(...){
error = true;
}
0
Could I make like if you type in a letter or special character it says : Invalid number, please try again? and than you can type number again. This is my code: (First day of learning C++ so it could be easy but Im still noob :P
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int x;
int main () {
cout << endl << "Type any number and you will get a random number between 1 and your number: " << endl << endl;
cin >> x;
srand(time(0));
cout << endl << "Your random number is: " << 1 + (rand() % x) << endl;
}
0
Well I guess Im stupid but I cant get it to work lol
0
Thank you so much, exactly what I was looking for and I actually needed it for other projects too!