error handling

0 Glenn Walker · November 8, 2014
I am having a little trouble with error handling for a string input.  What I am after is to force the user to input something into the string, such that if they just hit the enter key then the error handling will kick in and for them to input something.  It does work, but only if I hit enter twice.  I have tried a host of different things, like making the while argument: while(name.length() < 1 || name == "./".  But no matter what, I always end up with having to press the enter key twice to get the desired output.  Could anyone give me some idea of how this could be handled?

The input goes something like this (actually, exactly like this):

string Inventory::setName(string name)
    cout << endl << "Enter the item name: ";
    getline(cin, name);
    //error handling
    while (name.length() < 1)
        cin.clear(); //clear the cin error state
        cin.ignore(INT_MAX, '\n'); //discard characters in stream
        cout << endl << "Error, you must enter a name: ";
        getline(cin, name);

    return name;

Post a Reply


Oldest  Newest  Rating
0 Glenn Walker · November 10, 2014
Than ks, I will give that a try and see what it does for me.  Sometimes things get a little (lot) past me.
-4 Andreas Nilsson · November 8, 2014
I'm not really sure about taking a string as an argument and then changing it depending on the input of the user, but fault in your program is this line:

cin.ignore(INT_MAX, '\n'); //discard characters in stream 

it says ignore everything user inputs until \n (pressing the enter key). So the instruction:

cout << endl << "Error, you must enter a name: ";

will not be executed until you press enter again.

I think you simply misunderstood the cin.ignore command.
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator