Input to y2 skipped during operation. Why?

 #include <stdio.h> #include <stdlib.h> int main (void) { char buffer [5] = {0}; char y1 = 0, y2 = 0, y3 = 0; printf("Will you use characters (y/n) ?"); y1 = getchar(); printf("Will you use big characters (y/n) ?"); y2 = getchar(); printf("Will you use numbers (y/n) ?"); y3 = getchar(); printf("Enter your password ?"); scanf("%4s", buffer); printf("%c\r\n", y1); printf("%c\r\n", y2); printf("%c\r\n", y3); printf("%s\r\n", buffer); printf("done."); return EXIT_SUCCESS; } 

    2 answers 2

    It reads the key press <Enter> .

     #include <stdio.h> #include <stdlib.h> int main (void) { char buffer [5] = {0}; char y1 = 0, y2 = 0, y3 = 0; printf("Will you use characters (y/n) ?"); y1 = getchar(); while(getchar() != '\n'); printf("Will you use big characters (y/n) ?"); y2 = getchar(); while(getchar() != '\n'); printf("Will you use numbers (y/n) ?"); y3 = getchar(); while(getchar() != '\n'); printf("Enter your password ?"); scanf("%4s", buffer); printf("%c\r\n", y1); printf("%c\r\n", y2); printf("%c\r\n", y3); printf("%s\r\n", buffer); printf("done."); return EXIT_SUCCESS; } 
    • How to fix? another function? I did the same with scanf ! - biggy
    • 2
      And I also brought the solution - see the source ... My version, by the way, allows input of the type yes , no :) - will take only the first character. - Harry
    • thank! I just got distracted) - biggy

    The getchar function reads all characters from the stream, including spaces, newlines, etc.

    Instead of this function, use the scanf function. For example,

     scanf( " %c", &y1 ); ^^^^ 

    Pay attention to the space before the % character. It serves to skip the characters of the spaces in the input stream.

    Also, when displaying to the console, there is no need to use the carriage return symbol. Enough to write

     printf("%c\n", y1); ^^^^ 
    • Thank! I did not even know. - biggy
    • @biggy Not at all. Ask more. :) - Vlad from Moscow