比较 std::字符串与常量 vs 比较 char 数组与常量 In C++.
Comparing std::string with constants vs comparing char arrays with constants In C++
我正在尝试进行一些文本冒险以掌握C++。
cin >> keyboard1;
if ((keyboard1 == "inv")inventory(inv);
如果 keyboard1 是一个字符串,这将起作用,但如果它是一个字符数组,这将不起作用,这是因为我没有在常量末尾包含 null 吗?
假设您的代码如下:
int main(int argc, char *argv[])
{
std::string s;
std::cin >> s;
std::cout << s << std::endl;
if (s == "inv") {
std::cout << "Got it" << std::endl;
}
return 0;
}
由于 stl 类string
重写==
运算符的方式,因此这按预期工作。
您不能期望以下代码正常工作:
int main(int argc, char *argv[])
{
char *s = (char *)calloc(10, sizeof(char));
std::cin >> s;
std::cout << s << std::endl;
if (s == "inv") {
std::cout << "Got it" << std::endl;
}
return 0;
}
因为您正在比较 s,这是字符串开始到常量字符串的地址(顺便说一下,编译器会自动以 null 结尾)。
你应该使用 strcmp 来比较 "c 字符串":
int main(int argc, char *argv[])
{
char *s = (char *)calloc(10, sizeof(char));
std::cin >> s;
std::cout << s << std::endl;
if (strcmp(s, "inv") == 0) {
std::cout << "Got it" << std::endl;
}
return 0;
}
这行得通。
不,它不起作用的原因是您将比较表示每个字符串的内存地址。请改用strcmp
/wcscmp
。
比较字符串和常量工作的原因是字符串类将定义一个相等运算符(例如 bool StringClass:operator==(const char* pszString)
)。
如果keyboard1
是一个char数组,那么if (keyboard1 == "inv")
正在执行一个简单的指针比较(两者都变成char*
)。
当keyboard1
是字符串时,如果存在operator==(cosnt string&, const char*)
,它可以调用,否则,如果字符串具有非显式构造函数string(const char *s)
,则常量"inv"
将被隐式转换为字符串对象,并operator==(const string&,const string&)
应用。
相关文章:
- 禁止显示由于常量为零而比较始终为假的警告
- 将收到的 usart uint8_t* 数据与常量字符串进行比较
- C++,如何使用常量对象和非常量对象进行比较?
- 为什么 std::stable_sort() 的比较函数的参数必须是设置常量?
- 可作为常量调用的比较对象
- C++中是否有任何常量可以用作比较中的最小值/最大值
- 为什么常量字符[]和常量字符*之间的比较不同
- 比较字符和常量字符串
- 如何在 C++ 类中重载 'less than' 运算符以比较常量?
- 将非静态数据成员与常量成员进行比较
- 比较字符和常量字符
- 比较常量字符* 与字符(无法使用 strcmp 进行比较)刽子手游戏
- 将常量和变量与左边的常量进行比较有什么好处
- 私有成员的常量访问器之间的比较
- C++中易失性成员函数与常量成员函数的比较
- c++omp,比较参数和常量
- 如何举例来反驳“==”用于比较“常量字符*”的用法
- 将浮点数与常量进行比较时出现奇怪的行为
- 如果您意外地使用布尔运算符 (||, &&) 比较常量,则发出警告
- 比较常量指针和非常量指针