scanf function seems to be skipped in c

后端 未结 5 470
星月不相逢
星月不相逢 2020-12-06 03:43

I am new to c language, and I tried this code below, but it seems scanf has been skipped, when I run this code, it only asked me enter name and age and skipped the lines bel

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 04:12

    Change

    scanf("%c", &sex);
    

    to

    scanf(" %c", &sex);
           ^
          space
    

    and

    scanf("%c", &status);
    

    to

    scanf(" %c", &status);
           ^
          space
    

    The problem is because of trailing newline characters after your second call to scanf(). Since it is of %d type specifier, when you press Enter A newline character ( '\n' ) is left in the stream and the next scanf() tries to read that newline character, and thus, it seems as though it just skipped input, but in fact, it read the newline character.

    So, the newline character is stored in the variable sex, and thus, it skips asking you for input for that variable.

提交回复
热议问题