Cin >> Numbers or letters ONLY | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Cin >> Numbers or letters ONLY

Is there a way to block numbers or letters depending on the task that is given? For example, when the function is asking for input to define the variable "age", the user can use numbers only.

16th May 2017, 10:38 AM
Azmor EM
Azmor EM - avatar
6 Answers
+ 8
// Ya'll mean something like this? #include <iostream> #include <string> int main() { int number; while (true) { std::cout << "Please input a number : "; std::cin >> number; if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(512, '\n'); std::cout << "Error. Only numerical values accepted." << std:: endl; } else break; } std::cout << number; }
16th May 2017, 3:43 PM
Hatsy Rei
Hatsy Rei - avatar
+ 4
@Azmor I'm on Visual Studio cuz. :>
16th May 2017, 3:55 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
write up a warning to user that if user inputs words, then the system will automatically pick up random value. which it will, because if we input a word in a int variable it takes garbage value.. hope you got it buddy.
16th May 2017, 11:03 AM
DEVIL kingg
DEVIL kingg - avatar
+ 1
Thats perfect, Rei. Although you don't need to add #include <string> when using <iostream>.
16th May 2017, 3:50 PM
Azmor EM
Azmor EM - avatar
0
It is not about the error, but rather a hypothetical question. Right now I'm working towards that part of the code. I think I can solve this problem by pre-defining "age" with a number range between 0 and 100, but the user could still enter letters instead.
16th May 2017, 10:44 AM
Azmor EM
Azmor EM - avatar
0
Thanks, James & Kingg. This gave me a direction to work with
16th May 2017, 11:29 AM
Azmor EM
Azmor EM - avatar