有许多解决方案可以解决您的用户输入问题。我建议你一次读一行 fgets() 并解析它 sscanf() :
fgets()
sscanf()
#include <ctype.h> #include <stdlib.h> #include <string.h> #include "knapsack.c" int main() { char input[100]; listitemptr k2 = NULL; int i, returnval = 0; char command; for (;;) { printf("> "); if (!fgets(input, sizeof input, stdin)) break; i = strspn(input, " \t\n"); /* skip blanks */ command = input[i++]; if (command == '#' || command == '\0') { /* ignore comment lines and blank lines */ continue; } if (command == 'q' && input[i] == '\n') break; } if (command == 'p') { KnapsackPrint(&k2); continue; } if (command == 'a') { int item; if (sscanf(input + i, "%i", &item) != 1) { printf("invalid input\n"); continue; } KnapsackAdd(&k2, item); continue; } // add more commands printf("unknown command: %c\n", command); } return returnval; }