Terminate input on '|'

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

User avatar
cplusplusnoob
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 33
Joined: Sun Mar 08, 2009 2:40 pm
Location: Iowa city, Iowa

Re: Terminate input on '|'

Post 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.
I'm not modest, I'm brutally honest.
K-Bal
ES Beta Backer
ES Beta Backer
Posts: 701
Joined: Sun Mar 15, 2009 3:21 pm
Location: Germany, Aachen
Contact:

Re: Terminate input on '|'

Post by K-Bal »

Add an "return 1;" at the end of the if-case or you could add a "break;" at the same spot.
User avatar
cplusplusnoob
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 33
Joined: Sun Mar 08, 2009 2:40 pm
Location: Iowa city, Iowa

Re: Terminate input on '|'

Post by cplusplusnoob »

thank you it works you are the man. ;)
I'm not modest, I'm brutally honest.
K-Bal
ES Beta Backer
ES Beta Backer
Posts: 701
Joined: Sun Mar 15, 2009 3:21 pm
Location: Germany, Aachen
Contact:

Re: Terminate input on '|'

Post by K-Bal »

cplusplusnoob wrote:thank you it works you are the man. ;)
:lol:
Post Reply