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
1.2k views
in Technique[技术] by (71.8m points)

c - Program is skipping fgets without allowing input

Basically as the title says.. When my program is run from the console, it'll ask if you'd like to encrypt or decrypt.. and when I input e or E, it creates a new blank line (until I input some kind of text), then shows the "enter the text" and "enter the key" lines all at once..

So, in the console it would look something like:

Would you like to (E)ncrypt or (D)ecrypt? e

asdf jkl; <---- random user input to get the program to continue..

Enter the text you would like to encrypt : Enter a key to use for encryption : (user input)

and then the program exits..

//message to be encrypted
char text[250]; 
//word to use as the key
char key[50];
//stores the encrypted word
char encrypted[250];

char answer;
printf("Would you like to (E)ncrypt or (D)ecrypt? ");
scanf(" %c", &answer);

if(answer == 'e' || answer == 'E')
{
    printf("Enter the text you want to encrypt : ");
    fgets(text, 250, stdin);

    printf("Enter a key to use for encryption : ");
    fgets(key, 50, stdin);

    printf("Encrypted text : ");

    //code that encrypts the text here      
}

So the problem, then, is that it's skipping the fgets entirely and not waiting/allowing the user to input any answers.. why for?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The line scanf(" %c", &answer); is leaving a newline in the input buffer which is taken by fgets. The leading space in " %c" consumes leading whitespace but not trailing whitespace.

You can get rid of the newline with the "%*c" format specifier in scanf which reads the newline but discards it. No var argument needs to be supplied.

#include <stdio.h>

int main(void)
{
    char answer;
    char text[50] = {0};
    scanf(" %c%*c", &answer);
    fgets(text, sizeof text, stdin);
    printf ("%c %s
", answer, text);
    return 0;
}

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

...