<分区>
我在另一个函数中使用 fgets
来返回有效数据,因为我有一个菜单列表并且为每个函数写出 fgets
变得重复。我传递了一个字符数组 result[]
,它似乎总是 sizeof 8,这导致我的数据被剪裁。
void get_input(char result[]) {
if(fgets(result, sizeof(result), stdin) == NULL) { // sizeof is ALWAYS 8!
read_rest_of_line();
printf("\n");
} else
clearbuffer(result);
}
void get_valid_input(char result[]) {
get_input(result);
while(result == NULL || result[0] == '\n') {
printf("Enter a valid input or quit with CTRL+D\n");
get_input(result);
}
/* remove newline replace with nul terminator */
result[strlen(result)-1] = '\0';
}
正在执行:
char equipment_id[7];
char equipment_name[31+1];
char equipment_quantity[sizeof(long)];
long quantity;
printf("New ID: ");
get_valid_input(equipment_id);
printf("Please enter the equipment name: ");
get_valid_input(equipment_name);
printf("Please enter the total quantity: ");
get_valid_input(equipment_quantity);