"cin" Problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mohaakilla51
    New Member
    • Jul 2007
    • 39

    "cin" Problem

    OK, so I am creating a program to go along with a lesson from a book C++: A Dialog. So anyway, the program is supposed to get a variable number of pumpkin weights, sort them, and rank them based on which one is heavier. I know the way I am doing it is not efficeint at all, as I sort it in ascending order and then read it backwards, but that is not my problem. The problem is, in the following loop, if I enter anything but a number, then it repeats the loop endlessely, not letting the user input a value... can anyone tell me why this is?
    [code=cpp]
    while(currentpu mpkin!=0)
    {
    cout << "Enter pumpkin weight (0 to end): ";
    cin >> currentpumpkin;
    if(currentpumpk in!=0)
    pumpkin.push_ba ck(currentpumpk in);
    }
    [/code]
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    When you cin >> to an integer, the input stream is expecting an integer. So if, say, it finds a character, or anything that's not an integer, it flips out. "You didn't give me an integer! Come on!" That sort of thing.

    What actually happens is that the input stream enters the fail state, and can't be expected to run correctly. In order to fix it, you need to use the function cin.clear(). That will reset the input stream to normal mode. However, whatever caused it to enter the fail state is still in the stream - so you must use cin.ignore() to get rid of that erroneous character (or characters).

    Basically, when validating input, use a while loop with the condition while (!cin), which automatically keeps going while cin is in the fail state. Ask for input just before the loop (or use a do...while loop and ask inside), and inside the loop, use the cin.clear() and cin.ignore() commands. This will keep prompting the user for input until they enter correct data.

    Comment

    • mohaakilla51
      New Member
      • Jul 2007
      • 39

      #3
      thank you... that is what I needed to know,; so you would want me to make a loop like this:
      [code=cpp]
      while(!cin)
      {
      cin.clear();
      cin.ignore(1);
      cin >> temp;
      }
      [/code]
      In that situation, it doesn't ever actually give the user a chance to input on the screen until the ignore(1) has gone through everything, am I correct?

      Comment

      Working...