【发布时间】: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 的可能重复项。我怀疑这是否是重复的规范问题,但它确实出现在相关列表中。