Previously I’m a C programmer(wanna know more about system programming but don’t wanna go into assembly so i choose C) more but later on in my University I have to take C++ , I’m actually having a hard time on using the cin and cout object as it has some changes compare to my trusted printf() , scanf() , getchar() macro in C . Here’s the code.
The Code
int main(void)
{
using namespace std;
cout << "What is the number?\n\n";
cout << "#Number :";
cin >> num;
while(cin.fail())
{
cin.clear();
cin.ignore(1000 , '\n');
cout << "Please enter a number\n\n";
cout << "#Number :";
cin >> num;
}
return 0;
}
The Question
1.)I want this code to ask for a number from user ( less than and more than or equal to 0) , when user enter a character or string , i want it to alert user about it , clear the input buffer and reprompt user for a new value until it’s a number.
2.)So i just googling around and find a page preaching the method , so i just follow the way but it failed . I’ve no idea why once i run this code , type in a character it will causes infinite looping of the output Please enter a number.Any mistake done by me in this code??
Thanks for spending time reading my problem
P/S : I’m using CodeBlocks with minGW compiler.
You don’t say how it failed, so it’s difficult to say what your problem
is. The fact that you never declare
numis one obvious problem. Andit will fail if you enter a line longer than 1000 characters as well.
A more idiomatic solution in C++ would be to read the input line by line, using
std::getline, and then usingstd::istringstreamto convert the line into a number.