1

I have a question on some commands for cin. I'm still very new to c++ so bear with me.

I'm doing a simple calculation program where the user inputs a value and the program does a calculation with the input. I'm attempting to create a loop that checks the input to ensure the user inputted and number. After some research I found that using cin.clear and cin.ignore will clear the previous input so the user can input a new value after the loop checks to see if its not a number. It works well, except when the user inputs a word larger then 1 letter. It then loops and removes each letter one at a time until the previous cin is cleared. Is there a way to remove the entire word rather then one character at a time? I feel I have incorrectly interpreted what the cin commands actually do.

Here is the code in question:

//Ask the user to input the base
cout << "Please enter the Base of the triangle" << endl;
cin >> base;

//A loop to ensure the user is entering a numarical value
while(!cin){

    //Clear the previous cin input to prevent a looping error
    cin.clear();
    cin.ignore();
    //Display command if input isn't a number 
        cout << "Not a number. Please enter the Base of the triangle" << endl;
        cin >> base;
}
indiv
  • 17,306
  • 6
  • 61
  • 82
Dave555
  • 11
  • 2
  • How is 'base' defined? – marco6 Jan 19 '15 at 18:42
  • Base was defined as a double in the global section – Dave555 Jan 19 '15 at 18:46
  • 1
    This Q&A may help to solve your problems: [How to test whether stringstream operator>> has parsed a bad type and skip it](http://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it) – πάντα ῥεῖ Jan 19 '15 at 18:47
  • 1
    I've generally found that the best way to go is to read a whole line of input as a string, then parse it yourself (this way you're in complete control of detecting any invalid input). – Cameron Jan 19 '15 at 19:23

1 Answers1

1

I think you could get the answer in many ways on the net. Still this works for me:

#include <iostream>
#include <limits>

using namespace std;

int main() {
    double a;
    while (!(cin >> a)) {
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "Wrong input, retry!" << endl;
    }
    cout << a;
}

This example is simpler than the one linked in the comments since you are expecting input from the user, one input per line.

indiv
  • 17,306
  • 6
  • 61
  • 82
marco6
  • 352
  • 2
  • 12
  • 1
    This does do the same thing as my previous mentioned code. However When I run it it still is giving similar results. If I enter a word the is 4 letters long, the loop runs 4 times outputting the error message "Not a number" 4 times before the user can input another value. I guess that's what I'm really trying to avoid. – Dave555 Jan 19 '15 at 19:13