+ 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.
6 ответов
+ 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;
}
+ 4
@Azmor I'm on Visual Studio cuz. :>
+ 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.
+ 1
Thats perfect, Rei. Although you don't need to add #include <string> when using <iostream>.
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.
0
Thanks, James & Kingg. This gave me a direction to work with