Thread: cin.get(); not working with my switch statement

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    2

    Question cin.get(); not working with my switch statement

    I am new to programming and ran into an interesting problem. I wrote a simple program to try out using switch statements and at the end of the program I put cin.get(); to make the program wait for the user to press return. When I run the program, it'll do everything fine except it skips over cin.get();. I am using C++ 2008 Express Edition to write, compile and run my code. Here is my code.

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int num;
    	cout<<"Please pick a number from 1 to 3: ";
    	cin>> num;
    	switch ( num )
    	{
    	case 1:
    		cout<<"You are #1!\n";
    		break;
    	case 2:
    		cout<<"2 is the 2nd loneliest #...\n";
    		break;
    	case 3:
    		cout<<"3rd times a charm!\n";
    		break;
    	default:
    		cout<<"I did not understand you input.\n";
    		break;
    	}
    	cin.get();
    }
    Thanks for everyone's help! :-D

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    The problem is that you use cin >> num to read in the number and the user types the number and hits <enter>. The number is read in, but the newline from the <enter> is still in the input stream.

    When you call cin.get(), it gets one character from the input stream. In this case it gets the leftover newline character.

    One solution is to call cin.ignore() to ignore that newline, and then cin.get() will try to get a character and wait for the user to type some more. I would put cin.ignore() after all calls to cin >> just in case, since it won't hurt.

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    2
    Thank you Daved! It worked perfect!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. switch statement
    By guillermoh in forum C Programming
    Replies: 5
    Last Post: 03-10-2008, 02:17 PM
  2. Switch statement problem
    By jalex39 in forum C Programming
    Replies: 6
    Last Post: 03-08-2008, 04:05 PM
  3. switch case statement
    By stanlvw in forum C++ Programming
    Replies: 3
    Last Post: 02-26-2008, 05:06 AM
  4. Equivalent of less than in a switch statement?
    By Diamonds in forum C++ Programming
    Replies: 5
    Last Post: 10-14-2002, 07:14 PM
  5. switch statement / command line
    By Unregistered in forum C Programming
    Replies: 5
    Last Post: 12-20-2001, 04:21 PM