Search code examples
cgetcharenterletter

Checking if input is a ENTER without losing the first character in C


I have a program with alot of data stored in a file and gets loaded into structs.

I have an option so the user can change some information but since I don't know what he wants to change I need to printf and scanf all the information of the item he wants to change.

This is a part of the program:

char check;
    
if(p->vetor.id == jogo){
            
    printf("Reference: %d\n", jogo);
        fflush(stdin);
    printf("\nTeam 1: ");
        if(getchar() != '\n'){ // METHOD 1
            gets(p->vetor.eqTeam1); 
        }
        fflush(stdin);
        
    printf("\nTeam 2: ");
        if(scanf("%c", &check) && check != '\n'){ //METHOD 2
            gets(p->vetor.eqTeam2);
        }
        fflush(stdin);
}

It checks if the input is a ENTER (and it works) but when I write something there it "eats" the first letter because it needs to check before if is a ENTER or not, is there a way to give the lost letter back to the gets() ?

Thanks for your help.


Solution

  • Don't use scanf and never again use gets.

    Your problem can be solved by just using fgets

    printf("\nTeam 2: ");
    fflush(stdout);
    char input[256];  // same size of eqTeam
    fgets(input, sizeof(input), stdin);
    if (input[0] != '\n') {
        strcpy(p->vetor.eqTeam2);
    }
    

    This will always read in a full line, but if the first character of the line is a newline, the user just pressed enter. If the first char is something else, the input is copied to the correct location. Note that the input buffer must be of a suitable size, here I just guessed one that is for sure not correct (but I lack the necessary info)

    And one more thing, never flush stdin, you have to fflush(stdout) as fflush is an output operation.