Search code examples
clinuxubuntugetchar

Press ENTER to continue (Linux & C)


I am getting crazy here attempting to do something I thought it would be easy... :-) Hopefully you guys can help me out.

This a C function written for a Linux Ubuntu...

All I need is to show a confirmation message and I expect the user to hit ENTER to continue.

    #include <stdio.h>
    #include <time.h>

    void setDeposit(int account, int amount)
    {
        printf("You have successfully transfered %d EUR to the account number %d\nPlease press ENTER to continue\n", account, amount);
        getchar();

    }

The application "ignores" the getchar() and simply moves on.

EDITED

Including the entire program as requested in the comments:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rbs-accmgr.c"
#include "rbs-graphics.c"
#include "rbs-struct.c"

//Main application function
int main()
{
    //Creating the application control instance
    application a = {1, 0, 0};

    //Populating the customer information with the login interface information
    customer c = {1234, "John", "Deer", 0};

    //Clearing the terminal window
    system("clear");

    //Keeps the application running as long as the user doesn't hit option 9 (Quit)
    while (a.status == 1)
    {
        //Displaying the graphic objects
        displayBanner();
        displayMenu();
        scanf("%d",&a.selectedOption);
        displayBanner();

        switch(a.selectedOption)
        {
            //Deposit
            case 1:
                printf("\nHow much would you like to deposit?\n");
                scanf("%d",&a.operationAmount);
                setDeposit(c.account, a.operationAmount);
                break;

            //Wrong option
            default:
                a.status = 0;
                break;
        }

        //Making sure all variables are zeroed
        a.operationAmount = 0;
    }

    return 0;

}

What am I doing wrong here?

Thanks!


Solution

  • Please try the one below and let me know. I think that getChar is used by that scanf you wrote. A while reading a separate char can rule that out. I wrote \r in case you use other operating systems.

    void setDeposit(int account, int amount)
    {
        printf("You have successfully transfered %d EUR to the account number %d\nPlease press ENTER to continue\n", account, amount);
    
        char myChar = 0;
        while (myChar != '\n' && myChar  != '\r') { 
            myChar = getchar(); 
        }
    }
    

    Detailed information about the case can be found within this thread.