使用 strtok() 的错误字符串比较
Faulty string comparison using strtok()
#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
。
相关文章:
- 由cin中的字符串中未捕获空白引起的分割错误
- 将 GetLastError() 转换为带有错误字符串的异常
- Rapidjson 解析错误:字符串 (207) 中的编码无效
- 尝试对字符串[数组]>>cin 并出现错误(" "字符串下标超出范围")
- 如何检索 DirectX 9 的错误字符串
- 从 C++ => C 包装的 API(多线程)传输错误字符串
- 错误字符串下标超出c++范围
- 获取Openssl证书错误中的错误字符串
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 语法错误字符串方法C++
- 对于静态错误字符串,哪个的内存/性能效率更高,或者有替代方案
- 使用 strtok() 的错误字符串比较
- C++ 中的运行时错误字符串声明
- 我收到错误:字符串声明上的 C2501
- GCC:为什么一行代码中的错误(字符串和NULL的比较)会导致一长串错误消息
- 错误C2059:语法错误:'字符串'
- 致命错误:字符串:没有这样的文件或目录编译终止
- C++错误:字符串下标超出范围
- 这里面有什么错误?字符串赋值
- 是否有标准的方法来查询EGL错误字符串