【问题标题】:Program ignores some functions in order程序按顺序忽略了一些功能
【发布时间】:2014-04-23 00:42:43
【问题描述】:

我创建了一个可变大小的数组 (VLA),我想在 for 循环中使用 fgets 函数来填充它。然而程序传递了一些函数,它奇怪地忽略了第一个 fgets 动作。

我的代码是;

void editorMain(void)
{
    printf("Please enter the number of items:  ");
    scanf("%u", &itemQuantity);
    printf("\n\n");

    char itemNames[itemQuantity][ITEM_NAME_LEN+1];

    memset(&itemNames, 0, sizeof(itemNames));

    printf("Please enter the names of items:  \n");

    char line[ITEM_NAME_LEN+1];

    memset(&line, 0, sizeof(line));

    for (int i = 0; i < itemQuantity; ++i) {
        printf("#%d:  ", i + 1);

        memset(&line, 0, sizeof(line));

        fgets(line, ITEM_NAME_LEN+1, stdin);

        for (int a = ITEM_NAME_LEN+1; a >= 0; --a) {
            if (line[a] == '\n') {
                line[a] = 0;
            }

            else;
        }

        snprintf(itemNames[i], ITEM_NAME_LEN+1, "%s", line);
    }
...
}

然后输出;

Please make a choice:  2

Please enter the number of items:  4


Please enter the names of items:  
#1:  #2:  Marlboro
#3:  Parliament
#4:  Winston

Please enter the prices of items:  
#1:  25
#2:  950
#3:  1000
#4:  800
  ................... AVAILABLE ITEMS oo

         #           Item Name          Price
         =           =========        =======

         1.                           0.25 TL
         2.           Marlboro        9.50 TL
         3.         Parliament       10.00 TL
         4.            Winston        8.00 TL

  Enter your item selection:  

你有什么建议?

【问题讨论】:

  • 常见问题; scanf() 将换行符留在缓冲区中,因此 fgets() 读取到换行符,这让您感到困惑。可能最好始终使用fgets()sscanf() 将第一行转换为数字。关于这类问题还有很多其他问题。
  • When I run my program, fgets() is ignored and scanf() doesn't input data to structure 的可能重复项。我怀疑这是否是重复的规范问题,但它确实出现在相关列表中。

标签: c arrays fgets


【解决方案1】:

scanf("%u" 调用读取到换行符,但将该字符留在输入流中。当您调用您的第一个 fgets 时,它只会读取该换行符并为您提供一个空字符串。

有很多方法可以清除输入流,在这种情况下,您可以在scanf 之后添加一个对fgets 的虚拟调用。

【讨论】:

  • 谢谢,解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 2020-02-01
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
相关资源
最近更新 更多