使用各种输入大小的strtok

时间:2017-09-16 00:56:45

标签: c

所以我一直在研究一些没有按预期运行的代码。

下面的代码应该在只输入'h'时调用一个帮助函数,并在输入'q'时退出。我真的不明白什么时候按'h'它会出错:

printf("\n");
printf("Please input request (h-help, q-quit): ");

fgets(Input, 256, stdin);
char *array[256];
int count = 0;
char *token = strtok(Input, " ");
array[0] = token;
count++;

while(token != NULL)
{
    int i = 1;
    token = strtok(NULL, " ");
    array[i] = token;
    i++;
    count++;
}

if(count == 1)
{
    if(strlen(array[0]) == 2)
    {
        if(array[0] == 'h')
        {
            TRIGhelp();
            return 0;
        }
        if(array[0] == 'q')
        {
            return 0;
        }
    }
    else
    {
        printf("Error: Illegal input!");
    }
}

我使用了一个count变量,因为可以输入更大的字符串。例如,用户可以输入三个数字,或者字符串和三个数字等。

我尝试过使用strlen(array [0])== 1,它仍会打印出错误信息。 提前谢谢!

1 个答案:

答案 0 :(得分:0)

这里有很多问题,但我会专注于strtok,因为这就是你所要求的。

您正在使用fgets从输入中读取一行,但只对空格字符进行标记。每一行都会以换行符(\n)结束,那么你想用它做什么?用户也可以输入选项卡,在某些系统上,您可能会在行尾获得\r个字符。所以你可能想要

token = strtok(Input, " \t\r\n");

为了对所有空格进行标记,而不仅仅是空格。

相关问题