Thread: I'm having trouble with cin.get()

  1. #1
    Registered User
    Join Date
    Sep 2017
    Posts
    1

    I'm having trouble with cin.get()

    I've tried Googling this and can't find a solution yet. It's my understanding from class that cin.get() should accept any character, including tab, whitespace, or enter. However, when I'm using it, it ignores all input until enter/newline. I'm using Dev-C++ 5.11. If I don't use cin.ignore(), the program doesn't pause at cin.get(), which is expected. With cin.ignore(), cin.get() ignores everything (although the keys pressed appear on screen) until enter is pressed. Thank you.

    This is the program stripped down to just this relevant part.

    Code:
    #include <iostream>
    #include <string>
    #include <iomanip>
    
    using namespace std;
    
    int main()
    {
        float Tickets;
        
        cout << "\nPlease enter number of tickets sold: ";
        cin >> Tickets;
        
        cin.ignore();
        cout << "\nPress any key for results . . ."; cin.get();
    }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    cin.get() is still line buffered. What that basically means is that you will have enough control to type, and then, when you press enter, the entire line will eventually be sent to the program. For example, just try this program.
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
       char ch;
       while (cin.get(ch) && ch != '\n')
       {
          cout << ch << '\n';
       }
       cin.ignore(); // just to keep the window open
       return 0;
    }
    Just run that, enter in a long line and press enter... see how the input is fed to the program.

    Also note that cin.ignore() will discard exactly one character typed. The arguments you use will determine how many characters it discards and until some character, passed in, it encounters in the cin stream. If you only use it to keep the window open instead of using cin.get(), you won't really be able to tell, but the difference matters.
    Last edited by whiteflags; 09-26-2017 at 09:24 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I/O trouble again
    By Therry in forum C++ Programming
    Replies: 4
    Last Post: 04-13-2012, 09:20 PM
  2. having trouble help
    By ladylady in forum C++ Programming
    Replies: 2
    Last Post: 02-05-2011, 04:18 PM
  3. trouble with rt-app
    By quantt in forum Linux Programming
    Replies: 0
    Last Post: 09-28-2009, 05:21 AM
  4. Trouble with a lab
    By michael- in forum C Programming
    Replies: 18
    Last Post: 12-06-2005, 11:28 PM
  5. More trouble
    By Metalix in forum C Programming
    Replies: 12
    Last Post: 01-21-2005, 02:18 PM

Tags for this Thread