caramel1995
caramel1995

Reputation: 3055

Input validation using cin object and also clearing buffer(c++)

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.

Upvotes: 0

Views: 262

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 476970

The standard way to use formatting input is inside a conditional check on the operation itself. Also, you'll want to read an entire line and attempt to parse that rather than extract token by token. E.g. like this:

int num;

for (bool success = false; !success; )
{
  std::cout << "Please enter a number: ";

  std::string line;
  if (std::cin >> line)
  {
    std::istringstream iss(line);
    if (iss >> num) success = true;
  }

  if (!success) { std::cout << "Error!\n"; }
}

std::cout << "Thank you. You said: " << num << std::endl;

Feel free to add further diagnostic output in the error branch.

Upvotes: 0

James Kanze
James Kanze

Reputation: 153909

You don't say how it failed, so it's difficult to say what your problem is. The fact that you never declare num is one obvious problem. And it 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 using std::istringstream to convert the line into a number.

Upvotes: 2

Related Questions