【问题标题】:C program skipping part of function in switch statement. [duplicate]C 程序在 switch 语句中跳过部分函数。 [复制]
【发布时间】:2017-01-22 18:27:12
【问题描述】:

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

这里是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);
}

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

【问题讨论】:

  • 输入adminChoice 的值时,请记住以换行符结尾(Enter 键)。这个键被添加到输入缓冲区以从stdin 读取下一个你想要读取的东西。现在想想当这个换行符是stdin 输入缓冲区中的第一个字符时调用fgets 会发生什么。

标签: c function switch-statement


【解决方案1】:

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

您可以使用一种 hacky 方法并在 fetgs() 调用之前使用 getchar();。更好的选择是使用fgets() 来读取adminChoice(并使用sscanf()strto* 函数将其转换为整数)以避免scanf()。无论如何,在使用fgets() 时,您总是需要注意换行符。

【讨论】:

    猜你喜欢
    • 2015-05-02
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多