Thread: cin.get() problem

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    11

    cin.get() problem

    Ill explain first what the problem is and then show code:

    I recently discovered this site and read up on the cin.get(); so that text can be displayed before the program closes. I used it for when certain text is displayed, the user can press any key and then the program will process clrscr();. As you can see in my code, I used cin.get() two times. Once after rules are displayed and twice to clear die results. the cin.get() works for the first time I use it but it seems to skip the second cin.get().

    My program randomizes die results 1 to 100 and if you roll over a number you win your bet back+bet (DOUBLE).

    Code:
    #include<iostream.h>
    #include<stdlib.h>
    #include<conio.h>
    int main()
        {
        randomize();
        int money, bet;
        cout<<"\t\t\tBETTING GAME\n\n\n";
        cout<<"RULES:\n\n";
        cout<<"1. Enter your starting money when prompted.\n";
        cout<<"2. Type in your bet when prompted.\n";
        cout<<"3. Roll Higher then 65 and you win DOUBLE your bet.\n";
        cout<<"4. Roll a 1 or a 100 and win TRIPPLE your bet.\n";
        cout<<"5. If you want to chashout, enter in '9999' when the next\n";
        cout<<"betting time comes.\n";
        cout<<"6. After you cashout you will see if you won money or lost money.\n\n\n";
        cout<<"Press any key to continue once you've understood these rules.";
        cin.get();
        clrscr();
        cout<<"How much money would you like to start with?: ";
        cin>>money;
        clrscr();
        cout<<" ____________________\n";
        cout<<"|       MONEY        |\n";
        cout<<"|--------------------|\n";
        cout<<"     "<<money<<"           \n";
        cout<<"|____________________|\n";
        for(int die=random(100)+1;3==3;die=random(100)+1) {
            cout<<"How much do you want to bet?(9999 to quit): ";
            cin>>bet;
            if(bet==9999){
                break;}
            money=money-bet;
            cout<<"You rolled a "<<die;
            if(die>65) {
                money=money+bet+bet;
                cout<<" and won DOUBLE your bet.\n";
            }
            else if(die==1||die==100) {
                money=money+bet+bet+bet;
                cout<<" and won TRIPPLE your bet.\n";
            }
            else if(die>1&&die<66) {
                cout<<" Sorry, better luck next time.\n";
            }
            cout<<"Press any key to continue...";
            cin.get();
            clrscr();
        cout<<" ____________________\n";
        cout<<"|       MONEY        |\n";
        cout<<"|--------------------|\n";
        cout<<"      "<<money<<"            \n";
        cout<<"|____________________|\n";
        }
        return(0);
        }
    Also having problems with the else if's... when win double your bet, you only get your bet back and not the extra +bet. Cashout block not added yet til I know what the solution is to my current problem.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    11
    Well i geuss no one realizes what I want to fix so i'll say it simply:

    I used a cin.get(); in the beginning of the code so the program will continue what its doing and then runs into another cin.get() but it doesn't wait for me to press a key, it just skips it. How would i fix this?

  3. #3
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    The problem is with cin, cin leaves a trailing '\n' in the inputstream. So when you call cin.get() to have the user press enter, there already is a '\n' in the stream that will be picked up by cin.get(), and thus it sort of skips that. To fix do this:
    Code:
    // bla bla bla
    cin >> somevar;
    cin.ignore();

    About your problem with the doublebet and so on, it does exactly what you tell it to. Think about it, you tell the user to input how much to bet, you then take away that amount from their money. Then if you roll higher than 65 you add 2*bet. This is basicly what you are doing:
    Code:
    int var = 50;
    var -= 10;
    var += 20;    // After this var == 60.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    11
    i used the cin>>somevar; and cin.ignore(); and set somevar to 'a' and works. Next question, Is there a way to make it so that in my for loop if a certain condition is met within, the for statement will start from the beginning again rather then finish the remaining blocks of code contained in the for loop?

  5. #5
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    Use the continue keyword to have the loop start another pass.

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        for(int i=1; i<=5; i++)
        {
            if(i == 3)
                continue;
            cout << i << endl;
        }
        cin.get();
    }
    This will print
    1
    2
    4
    5

    Also I forgot to point these things out in your other post. You shouldnt use iostream.h, stdlib.h. Replace those with these lines:
    Code:
    #include <iostream>
    #include <cstdlib>
    using namespace std;
    And just so you know, C++ has a standard way of getting random numbers, search for rand() and srand().

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    11
    Quote Originally Posted by Shakti
    And just so you know, C++ has a standard way of getting random numbers, search for rand() and srand().
    Unfortunately Im using Borland C++ ver 4.52 (Old)
    and .h has to be included or it will not open, and the stdlib will only work =/

  7. #7
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    Get bloodshed's Dev C++. It is free and comes with a very good C++ compiler.

  8. #8
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Just something to note:
    Code:
        cout<<" ____________________\n";
        cout<<"|       MONEY        |\n";
        cout<<"|--------------------|\n";
        cout<<"      "<<money<<"            \n";
        cout<<"|____________________|\n";
    Could be written as:
    Code:
        cout<<" ____________________\n"
            <<"|       MONEY        |\n"
            <<"|--------------------|\n"
            <<"      "<<money<<"            \n"
            <<"|____________________|\n"
            <<flush;
    or even:
    Code:
        cout<<" ____________________\n"
              "|       MONEY        |\n"
              "|--------------------|\n"
              "      "<<money<<"            \n"
              "|____________________|\n"
            <<flush;
    I only mention because well I'm up way to early

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    11

    works as intended to work.. well sorta

    works as intended tho however, I was hoping to have \n for cin.get(); can be used over and over instead of adding cin>>var; cin.ignore(); .. still works thx for the help everyone.

    Code:
    #include<iostream.h>
    #include<stdlib.h>
    #include<conio.h>
    int main()
        {
        randomize();
        int money, bet, a;
        char pass='ok', ans;
        cout<<"\t\t\tBETTING GAME\n\n\n";
        cout<<"RULES:\n\n";
        cout<<"1. Enter your starting money when prompted.\n";
        cout<<"2. Type in your bet when prompted.\n";
        cout<<"3. Roll Higher then 65 and you win DOUBLE your bet.\n";
        cout<<"4. Roll a 1 or a 100 and win TRIPPLE your bet.\n";
        cout<<"5. If you want to chashout, enter in '9999' when the next\n";
        cout<<"betting time comes.\n";
        cout<<"6. After you cashout you will see if you won money or lost money.\n\n\n";
        cout<<"Press any key to continue once you've understood these rules.";
        cin.get();
        do{
        clrscr();
        cout<<"How much money would you like to start with?: ";
        cin>>money;
        a=money;
        clrscr();
        cout<<" ____________________\n"
        <<"|       MONEY        |\n"
        <<"|--------------------|\n"
        <<"     "<<money<<"           \n"
        <<"|____________________|\n"
        <<flush;
        for(int die=random(100)+1;3==3;die=random(100)+1) {
            if(money<=0) {
                cout<<"You are out of money. ";
                break;}
            cout<<"How much do you want to bet?(9999 to quit): ";
            cin>>bet;
            if((bet>money)&&(bet!=9999)) {
                cout<<"You cannot bet over the amount of money you have!\n";
                cout<<"Enter 'ok' to continue:...";
                cin>>pass;
                cin.ignore();
                clrscr();
                cout<<" ____________________\n"
                <<"|       MONEY        |\n"
                <<"|--------------------|\n"
                <<"     "<<money<<"           \n"
                <<"|____________________|\n"
                <<flush;
                continue;
                }
            if(bet==9999){
                break;}
            money=money-bet;
            cout<<"You rolled a "<<die;
            if(die>65) {
                money=money+bet+bet;
                cout<<" and won DOUBLE your bet.\n";
            }
            else if((die==1)||(die==100)) {
                money=money+bet+bet+bet;
                cout<<" and won TRIPPLE your bet.\n";
            }
            else if((die>1)&&(die<66)) {
                cout<<" Sorry, better luck next time.\n";
            }
            cout<<"Enter in 'ok' to continue:...";
            cin>>pass;
            cin.ignore();
            clrscr();
            cout<<" ____________________\n"
            <<"|       MONEY        |\n"
            <<"|--------------------|\n"
            <<"     "<<money<<"           \n"
            <<"|____________________|\n"
            <<flush;
        }
        if(money>a) {
            cout<<"You won a profit of "<<(money-a)<<".";}
        if(money<a) {
            cout<<"You lost "<<(a-money)<<".\n";}
            cout<<"Do you want to play again?(Y/N): ";
            cin>>ans;
        }while(ans=='y'||ans=='Y');
        return(0);
        }

  10. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    When these statements are executed:

    cout << "\nEnter a number: ";
    cin >> num;

    The program stops and waits for you to enter the data. Then, you enter the data and hit return. If you enter 10 and hit return, this is what your program sees:

    10\n

    After you hit return a '\n' character is entered and that becomes part of your input. However, cin>> is defined to stop reading when it encounters a '\n' character. So, your program reads 10 into your variable num, and after words the input stream looks like this:
    Code:
    10\n
       ^
    Your program actually keeps track of where it stopped reading your input, and as far as it's concerned there's still input left to be read at some future date, namely the '\n' character. Then, execution continues until this line is encountered:

    cin.get();

    That is an instruction to read in the next character in the input stream. If there are no characters in the input stream, then the program has to wait for the user to enter a character before the statement can be executed. However, in this case there is a character in the input stream, namely the '\n'. The result is: your program doesn't wait for the user to input anything because it still has stuff to read--there is still a '\n' left over from the earlier input. So, cin.get() happily reads that '\n', and as far as your program is concerned cin.get() has finished execution, so it's time to move on. Therefore, your program continues execution making it seem like it skipped that line.

    The solution? As was mentioned earlier, there is a function called ignore() that you can use:

    cin.ignore();

    That ignores the number of characters you indicate between the parentheses with the default being 1. So, the above line will ignore one character. If you include that after your cin>> line, then your stream will look like this:
    Code:
    10\n
        ^
    Then, when your program comes to this line:

    cin.get();

    there is no data to read from the input stream, so execution is halted until the user enters some data.

    The conclusion of that long explanation is that whenever you use cin>> and then subsequently use cin.get() or cin.getline(), you need to use cin.ignore() after the cin>> line.
    Last edited by 7stud; 07-28-2005 at 03:19 PM.

  11. #11
    Registered User
    Join Date
    Jul 2005
    Location
    US
    Posts
    6

    Thumbs up Great Explanation!!

    Bravo, 7stud! Thanks, your explanation is crystal clear to me. If you read the other post by Phan, I asked you to test ILoveVectors' sample codes:

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	char a, b, c;
    	cin >> a;
    	cin >> b;
    	cin >> c;
    	cout << a << "   " << b << "   " << c << endl;
    	cin.get();
    }
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	char a, b, c;
    	cout << "letter : ";
    	cin >> a;
    	cin.ignore(80, '\n');
    	cout << "letter : ";
    	cin >> b;
    	cin.ignore(80, '\n');
    	cout << "letter : ";
    	cin >> c;
    	cin.ignore(80, '\n');
    	cout << a << "   " << b << "   " << c << endl;
    	cin.get();
    }
    by typing "abcd" at the command prompt.
    It is another usage of cin.ignore() that I found is interesting also. I hope that you understand what ILoveVectors was talking about.

  12. #12
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    If you read the other post by Phan, I asked you to test ILoveVectors' sample codes:
    The "skipping problem" can't occurr when you are using cin>> to read in ints, which is what the code in question was doing.
    Last edited by 7stud; 07-28-2005 at 03:42 PM.

  13. #13
    Registered User
    Join Date
    Jul 2005
    Location
    US
    Posts
    6

    Lightbulb I see!

    Hey, I see what you mean now, 7stud. But how come it doesn't skip for int types?

  14. #14
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Because for numeric types, the >> operator is programmed to keep reading until it encounters whitespace(spaces, tabs, newlines) whereupon it stops. Then, when the next read occurs, the >> operator is programmed to skip leading whitespace, so if a \n is the next character in the stream, it is skipped.

    To summarize, for non char types, the >> operator:

    1) skips any leading whitespace
    2) stops reading when it encounters whitespace
    3) the stream position is marked so the whitespace character is the next character to be read.

    On the other hand, the getline() function:

    1) does not skip any leading whitespace
    2) stops reading when it encounters the specified terminating character, so it reads in any whitespace up until that point. The way getline() handles the terminating character is also different than the >>operator. getline() reads in the terminating character, but then discards it.
    3) the stream position is marked at a point just past the terminating character.

    Code:
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	
    	string str;
    	cout<<"enter some text: ";
    	getline(cin, str, '\n');
    
    	string str2;
    	cout<<"enter some more text: ";
    	getline(cin, str2, '\n');
    
    	cout<<str<<endl
    		<<str2<<endl;
    
    	return 0;
    }
    Note how the second getline() waits for user input. The second getline() does not read in the \n that is part of the first input, and therefore there is no skipping problem.
    Last edited by 7stud; 07-28-2005 at 06:06 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  2. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  3. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM
  4. cin.get(); problem
    By J.P. in forum C++ Programming
    Replies: 19
    Last Post: 12-14-2006, 07:07 AM
  5. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM