C 程序跳过 switch 语句中的部分函数。

标签 c function switch-statement

<分区>

我编写的程序太长,无法复制到此站点。但需要的内容将粘贴到网站中。

这是 switch 语句:

    void enterName();

    int adminChoice;
    printf("\nEnter Numeric Choice: ");
    scanf("%d", &adminChoice);

    switch(adminChoice)
    {
        case(1):
        {
            enterName();
        }
    }

这是实际的功能:

void enterName()
{
    FILE *fp = fopen("/home/matthew/Desktop/BBE.txt", "w");

    if (fp == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }
    char comment[100];

    printf("Enter, String\n");

    fgets(comment, sizeof comment, stdin);
    fputs(comment,fp);
}

程序会要求用户输入字符串。但是没有时间放入所需的字符串。它只是结束程序。

最佳答案

问题是 scanf() 留下一个 \n 字符终止 fgets()立即不阅读任何内容。 fgets() 会在看到换行符或 EOF 时停止读取。

您可以使用 hacky 方法并在 fetgs() 调用之前使用 getchar();。更好的选择是使用 fgets() 读取 adminChoice(并使用 sscanf()strto* 函数将其转换为整数),这样您就可以避免 扫描()。在任何情况下,使用 fgets() 时都必须注意换行符。

关于C 程序跳过 switch 语句中的部分函数。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41794616/

相关文章:

c - 将指向 int 数组的指针传递给 C 函数

php - 在 jQuery 脚本中使用 PHP 可以吗?

php - 计数功能在开关中不起作用

c# - 在 Switch 中向 Case 语句添加附加条件

Java 应用程序未将菜单打印到屏幕上

c - 如何在 C 中请求一个 int,然后将其减去 5

c - C程序的内存布局

java - 我如何翻译 printf ("%c",M);我的 DES 实现从 C 到 Java?

c - ARP 回复数据包不会更新 Ubuntu 上的 ARP 缓存

r tidycensus 下载所有 block 组