Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

C - trying to read a single char from stdin (and failing) w/ scanf / getchar

as a part of a homework assignment, I'm trying to read a single char from stdin, and act according to it:

char choice;

while (1) {
    printf("please enter [y]es, [n]o or [m]aybe: ");
    scanf("%c", choice);
    fflush(stdin);
    // validate input
    if (choice == 'y' || choice == 'n' || choice == 'm') {
        break;
    } else {
      printf("Please enter only 'y', 'n' or 'm'!
");
    }
}
// do something with the input
if (choice == 'y') {
    printf("you selected yes!
");
}

for some reason, scanf captures both the char and the line-feed after, thus it proceeds to do something with the input and then also prints the "Please enter only 'y', 'n' or 'm'!" line. If I enter several characters on the stdin, it will print that line for all of them, while also performing correctly for the first char. So, for example:

$ ./run
please enter [y]es, [n]o or [m]aybe: y<return>
you selected yes!
Please enter only 'y', 'n' or 'm'!
$ ./run
please enter [y]es, [n]o or [m]aybe: yes<return>
you selected yes!
Please enter only 'y', 'n' or 'm'!
Please enter only 'y', 'n' or 'm'!
Please enter only 'y', 'n' or 'm'!
$

Same thing happens if I use getchar. What am I missing? thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need a space between scanf(" and the %c for it to work correctly:

scanf(" %c", &choice);

And you also need to use &choice, not choice!

EDIT: While you're at it, you might want to look into do while() for that loop (unless the professor specifically said to use a break) - do while works great when validating user input!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...