Why does scanf function get automatically previous '\n' value and how can I escape from this event?

南笙酒味 提交于 2020-08-20 10:27:46

问题


I'm not new at writing code. But I'm just learning C language. I cannot understand this subject. Perhaps it is not an issue but now it is an issue for me. Would you please explain that?

Here is code, where I encounter with this:

#include <stdio.h>


int main(int argc, char *argv[])
{
    char letter;

    while (1)
    {
        printf("Enter a letter:\n");
        scanf("%c", &letter);

        switch (letter)
        {
            case 'a':
            case 'A':
            case 'e':
            case 'E':
            case 'i':
            case 'I':
            case 'u':
            case 'U':
            case 'o':
            case 'O':
                printf("%c is a vowel letter.\n", letter);
                break;
            case 'y':
            case 'Y':
                printf("%c is sometimes a vowel letter.\n", letter);
                break;
            default:
                printf("%c is not a vowel letter.\n", letter);
        }
    }

    return 0;
}

Output:

Enter a letter:
a
a is a vowel letter.
Enter a letter:

 is not a vowel letter.
Enter a letter:

回答1:


Change the format from "%c" to " %c" to make scanf discard all whitespace (as determined by isspace(), " \v\f\r\n\t" in the POSIX and C locales) before assigning the next character, whatever it may be.

Maybe a better alternative, read a whole line with fgets and then use sscanf to parse it instead.

As an aside, take care that scanf can always fail. On success, it returns the number of assigned arguments.
Also, I strongly suggest you read the scanf-manpage I linked above (or even better, the C standard on scanf), because there are quite a lot of pitfalls you may not know yet.



来源:https://stackoverflow.com/questions/26691924/why-does-scanf-function-get-automatically-previous-n-value-and-how-can-i-esca

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!