c - 从 switch case 或循环中的输入获取带空格的字符串

标签 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 循环或 switch case 中时:

        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? ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠

这些有什么问题吗?我使用 Visual Studio 。而我总是遇到麻烦。是关于这个的吗?

最佳答案

问题是 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;
}

关于c - 从 switch case 或循环中的输入获取带空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50127809/

相关文章:

c - 读取由 12 个数字组成的数组,每个数字之间有空格 - C 编程

php - 将文本分成两半,但在最近的句子处

javascript - 在 html 文本框中设置键盘插入符号位置

android - 触摸阶段行为问题

c - 如何更改当前代码以直接从 IDR 寄存器读取

c - 中断正在等待的 accept(),只是改变一个全局变量值

c - 为什么这个 y/n 程序没有输出

java - 在 HashSet 中搜索字符串数组中的任意元素

c - 使用 cbreak() 接收到两位数地址后,直接在数组位置打印数据; <curses.h> 和 getch();

c - 尝试删除节点会导致段错误