Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

getchar - 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
", jogo);
        fflush(stdin);
    printf("
Team 1: ");
        if(getchar() != '
'){ // METHOD 1
            gets(p->vetor.eqTeam1); 
        }
        fflush(stdin);
        
    printf("
Team 2: ");
        if(scanf("%c", &check) && check != '
'){ //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.

question from:https://stackoverflow.com/questions/65645387/checking-if-input-is-a-enter-without-losing-the-first-character-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't use scanf and never again use gets.

Your problem can be solved by just using fgets

printf("
Team 2: ");
fflush(stdout);
char input[256];  // same size of eqTeam
fgets(input, sizeof(input), stdin);
if (input[0] != '
') {
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...