JORDANO
JORDANO

Reputation: 724

Return false if char or string, but return true if input cannot convert to an integer. C++ Do while loop

Language: C++ (IDE: Visual Studios) How do I make a do while loop return true when a user inputs anything but an integer? I'm a little lost on how to do this.

#include <iostream>//pre processor directive
#include <string>
#include <iomanip>
using namespace std;//standard library

int main( )

double money=0;

do{
    cout << ("please enter your taxable income:\n") << fixed << setprecision(2) << endl;

    cin >> (money);

}while(money < 0 || );

Upvotes: 0

Views: 765

Answers (2)

JORDANO
JORDANO

Reputation: 724

I ended up just doing a try/catch statement, which basically involved me adding a new variable to the mix, which is the string "str":

    double money = 0; //initialized
    string str= ""; //initialized

    do{

        cout << "Please input an integer value" << endl;
        cin >> (str);

        try{
            money = stod(str);   //string to double
        }catch(...){  //inside the parenthesis, the "..." means to catch all exceptions.
            money = -1;    
            cin.clear();   
        }

    }while( money < 0);

This will catch anything that does not convert to a double, giving the value of money to equal -1. Otherwise, it will continue with the program.

Upvotes: 0

Jon Purdy
Jon Purdy

Reputation: 54971

istream defines a conversion to bool which indicates whether the last read was successful. You can use this to test whether parsing a double succeeded:

if (cin >> money) {
    // success
} else {
    // failure
}

If the stream is in a failed state and you want to retry reading—e.g., to prompt the user for a new value—then you can use the clear() member function to return the state to normal:

cin.clear();

However, this does not clear the input buffer, so you will end up reading the same data again. You can clear the input buffer until the next newline character:

cin.ignore(numeric_limits<streamsize>::max(), '\n');

Or you can read by lines instead, and use a stringstream to read individual values:

string line;
getline(cin, line);
istringstream stream(line);
if (stream >> money) {
    // success
} else {
    // failure
}

This has the advantage of forcing user input to be line-based—it’s token-based by default.

Upvotes: 5

Related Questions