使用 strtok() 的错误字符串比较

Faulty string comparison using strtok()

本文关键字:错误 字符串 比较 strtok 使用      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
   char stringbuf[256] = "add joe smith 120120120";
   char* cmd = strtok(stringbuf, " ");
   if (cmd == "add")
    printf("ADD command recognized!n");
   else
    printf("UNRECOGNIZABLE COMMAND!n");
   system("PAUSE");
}

我使用断点来检查每个变量包含的内容。cmd 已经"添加"了,它正在打印"无法识别的命令!

怎么了?

(cmd == "add")中,您正在比较指向字符的两个指针,而不是比较字符串。

如果要比较C++代码中的字符串,请使用 std::string 。如果要编写 C 样式的代码,请使用 strcmp