variables question

I am working on a project that is a calculator. I have the project done, but am trying to tweak the code due to one problem. When asked for a number, you put in a letter and it closes the program with erroneous data. I am trying to figure out how to do something similar to as follows.

Input number = program works as intended
Input letter = program recognizes this is not correct and asks to input a number only.

what I am using for the variable now is:

1
2
3
   double weight = 0;
   cout << "Enter your weight in pounds to one decimal point: ";
		cin >> weight;


Using this, it acts as explained above. What can i add to make sure it recognizes its not a number and asks for a number?
You could input to a string and check whether it's a valid number of not. If it is, convert it to a numeric type. There's various ways to check if a string represents a valid number. See here for examples.
http://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template <typename T>
T validated_input(std::string error_message)
{
    T value;
    while(not (std::cin >> value)) { //While input fails
        std::cout << error_message; //Output error message
        std::cin.clear(); //clear error state
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore errorneous input
    }
    return value;
}

//Usage
std::cout << "Enter your weight in pounds to one decimal point: ";
double weight = validated_input<double>("Enter floating point value!\n");
Enter your weight in pounds to one decimal point: Hello
Enter floating point value!
3.14
http://ideone.com/UJ52Lz
This is the purpose of the fail_bit in ios_base.
1
2
3
4
5
6
7
8
9
10
11
12
double weight = 0;
do {
    cout << "Enter your weight in pounds to one decimal point: ";
    cin >> weight;
    if (cin.good()) break;
    else if (cin.fail()) {
        cout << "Bad entry. Please try again\n";
    } else {
        cout << "Error on cin.\n";
        exit(1);
    }
} while (true);

Use operator bool instead of good() member function. .good() should be only used to check stream readiness for further inputs, not for checking success of already happened input
in your code:
4
5
    cin >> weight;
    if (cin) break;
Topic archived. No new replies allowed.