Page 2 of 2

Re: Terminate input on '|'

Posted: Sat Mar 21, 2009 6:20 am
by cplusplusnoob
programmerinprogress wrote:that worked very nicely ;)

a simple solution to a simple problem, funnily enough, i've never been able to get cin.clear() to work in the past, it's always just ignored my command to stop, therefore i've been trying to find a solution that worked around that.

But yours worked perfectly fine, so now theres no need whatsoever :)

also, a very clean loop was used, I may have been tempted to write a Do...while(str != "|"), but that's just a matter of preference (really just to eliminate an If statement from the mix)

here's how I would write this, now that my cin.clear() appears to work

Code: Select all

#include <iostream>
using namespace std;

int main() {

    int input;
    string str;

    do{

        cout << "Enter a number (| to quit): ";
        cin >> input;

        if(cin.fail()) {
            cin.clear();
            cin >> str;
            cout << "That was not a number" << endl;


        }
        else
        {
            cout << "You entered: " << input << endl;
        }



    }while(str != "|");

    return 0;
}

sorry I have a lot of homework right now but I finally got around to doing this program but when I did I can't quit it will only say that | is not a number.

Re: Terminate input on '|'

Posted: Sat Mar 21, 2009 6:32 am
by K-Bal
Add an "return 1;" at the end of the if-case or you could add a "break;" at the same spot.

Re: Terminate input on '|'

Posted: Sat Mar 21, 2009 12:08 pm
by cplusplusnoob
thank you it works you are the man. ;)

Re: Terminate input on '|'

Posted: Sat Mar 21, 2009 9:01 pm
by K-Bal
cplusplusnoob wrote:thank you it works you are the man. ;)
:lol: