c - C 中 strcmp() 的问题

标签 c strtok strcmp

char* mystr = calloc(25, sizeof(char));
fgets(mystr, 25, stdin); // I enter "6 7 *" in here, without the quotes

char* tok;
tok = strtok(mystr, " ");
while (tok != NULL) {
    if(strcmp(tok, "*") == 0)
        //It never meets this condition, but I don't understand why
    else
        //do something else here
    tok = strtok(NULL, " ");
}

问题是 strcmp(tok, "*") 永远不会返回相等的值,即使 tok 从原始字符串中读取星号。我不明白为什么它永远不满足这个条件。

最佳答案

您的 * token 可能还包含您为完成输入而键入的 \n 字符。将单个字符与以下之一进行比较:

  if(tok[0] == '*')

  if(strncmp(tok, "*", 1) == 0)

或将 \n 添加到分隔符列表中:

  tok = strtok(NULL, " \n");

关于c - C 中 strcmp() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19419338/

相关文章:

c - C中的半浮点转换算法?

c - 警告 : passing argument 1 of 'pushPost' makes pointer from integer without a cast [-Wint-conversion] in my infix to postfix progam

c - 读取文件并使用Strtok,某些字段读取成功,某些字段读取不成功

c - 读取 .ini 文件并在 C 中返回特定值

c - 如何最好地增强我的程序以利用 strcmp 的时序优化?

c - 将 strcmp 与数组一起使用

c - 当我的文件以文本开头时,fgets 读取三个 ''\n"

c++ - 预编译头是递归的吗?

c - 在游戏编程中设置屏幕分辨率

C strtok 分隔符返回 → ( 最后