Menu

Enter

studistudi
2007-12-18
2012-09-26
  • studistudi

    studistudi - 2007-12-18

    Hello @ all
    my English can be a bit bad;-)

    I'm new in CPP
    I use Windows Vista 32-Bit
    Here's my problem:
    first my program:


    include <iostream>

    using namespace std;

    int main ()
    {
    int eingabe;
    cout << "Give in something!" << endl;
    cin >> eingabe;
    cout << "You gave"
    << eingabe
    << "in.\n";

    cin.get ();

    return 0;
    

    }

    My problem is, when I give in Something and tip enter on the keyboard,
    the window will close a few moments later. But I don't want that the window
    close when I tip enter.

    Thanks for help

     
    • studistudi

      studistudi - 2007-12-18

      Thank you very much!

       
    • cpns

      cpns - 2007-12-18

      When you enter a number, say 123, the actual sequence of characters is (typically): 123<newline>. Because the right hand operand to the >> operator is an int, only the digit characters will be parsed, the <newline> is not part of the number and remains buffered ready for any subsequent input request. This stray <newline> thus immediately satisfies the subsequent cin.get() call.

      cin >> eingabe;
      cin.sync() ;

      or perhaps more portably:

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

      These solutions work even if for example a perverse user enters: 123!*&$<newline>. You still get eingabe == 123.

      Reading numeric data directly like this is problematic in a number of ways, see for example: http://www.augustcouncil.com/~tgibson/tutorial/iotips.html#directly, which suggests alternative methods (as well at plenty of other advice in I/O). Either way I suggest that you wrap your numeric input method in a function, so that you only need to make it robust once.

      Clifford

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.