Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

scanf

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\'!\n");
    }
}
// do something with the input
if (choice == 'y') {
    printf("you selected yes!\n");
}

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.

like image 917
sa125 Avatar asked Dec 24 '09 18:12

sa125


People also ask

Does Getchar read stdin?

getchar is a function in C programming language that reads a single character from the standard input stream stdin, regardless of what it is, and returns it to the program. It is specified in ANSI-C and is the most basic input function in C. It is included in the stdio. h header file.

What is the problem with Getchar in C?

What is the problem with getchar()? Getchar() is one of the function which is used to take input from the user. But at a time it can take only one character.. if the user give more than one character also,it reads only one character.

What can I use instead of Getchar in C?

Read a single character using the scanf() function Let's consider a program to read a character using the scanf() library function in C. As we can see, when we execute the above program, it takes a single character or group of characters using the scanf() library function instead of the getchar() function.

Is Getchar safe in C?

getchar() is a standard C function and is a safe function. you may come across non-standard function getch() or getche() if you are learning from multiple sources. Don't use them in your code.


1 Answers

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!

like image 178
Alex Marcotte Avatar answered Sep 18 '22 13:09

Alex Marcotte