从switch case或loop中的输入获取带空格的字符串

时间:2018-05-02 05:42:11

标签: c string input scanf fgets

我尝试使用此网站上的代码(how-do-you-allow-spaces-to-be-entered-using-scanf

           char name[15];         //or char*name=malloc(15);
           /* Ask user for name. */

            printf("What is your name? ");

            /* Get the name, with size limit. */

            fgets(name, MAX, stdin);

            /* Remove trailing newline, if there. */

            if ((strlen(name) > 0) && (name[strlen(name) - 1] == '\n'))
                name[strlen(name) - 1] = '\0';

            /* Say hello. */

            printf("Hello %s. Nice to meet you.\n", name);

当我在main中运行此代码时,它的效果非常好。输出是:

 What is your name? j k rowling
Hello j k rowling. Nice to meet you.

但是,当我将此代码放入while循环或切换开关时:

        char name[15];
        switch (choice) {
            case 1:
            printf("What is your name? ");

            /* Get the name, with size limit. */

            fgets(name, MAX, stdin);

            /* Remove trailing newline, if there. */

            if ((strlen(name) > 0) && (name[strlen(name) - 1] == '\n'))
                name[strlen(name) - 1] = '\0';

            /* Say hello. */

            printf("Hello %s. Nice to meet you.\n", name);


            break;  }

输出结果为:

What is your name? Hello . Nice to meet you.

所以,它不会等到输入一个字符串。也许fgets不起作用我不知道。

如何使此代码生效?或者使用所有空格从输入获取字符串的任何替代方法。我试过这个:

switch (choice) {
        case 1:
            printf("What is your name? ");
            scanf("%[^\n]s", name);
            printf("%s\n", name);  }

输出是:

What is your name? ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠

这些有什么问题?我使用visiual studio。我总是遇到麻烦。这是关于它的吗?

1 个答案:

答案 0 :(得分:1)

问题是stdin未正确刷新

您需要手动刷新它。 ( fflush()功能可用。但它有问题。)

以下是解决您的问题的示例代码。见working here

#include <stdio.h>
#define MAX 15

int main(void) {
    // your code goes here
    char name[MAX];
    char c;
    int choice=1;
    while(choice>0 && choice<3)
    {
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch(choice)
        {
            case 1:

                //Flush stdin
                while ((c = getchar()) == '\n');
                ungetc(c, stdin);

                printf("What is your name? ");
                fgets(name, MAX, stdin);
                if ((strlen(name) > 0) && (name[strlen(name) - 1] == '\n'))
                name[strlen(name) - 1] = '\0';
                printf("Hello %s. Nice to meet you.\n", name);
            break;

            case 2:
                printf("Your choice is case 2\n");
            break;
        }
    }
    return 0;
}