【发布时间】:2018-08-30 05:40:01
【问题描述】:
I/O 问题:
我被要求从用户那里获取输入并解析它。 问题是我的程序应该能够处理 任何 长度的输入,并将任何超过 256 个字符的输入行视为无效并相应地打印一条消息。
目前我使用fgets 接收输入行并使用strtok 稍后解析它,但是输入行很长会出现问题。
我该如何解决这个问题?
到目前为止我的代码:
char userInput[1024];
char *token = NULL;
while (!feof(stdin)) {
fflush(stdin);
if (fgets(userInput, 1024, stdin) != NULL) {
token = strtok(userInput, " \t\r\n");
if (token != NULL) {
if (strncmp(userInput, "fiver", 5) == 0) {
printf("5");
}
else if (strncmp(userInput, "four", 4) == 0) { printf("4");}
【问题讨论】: