比较 C++ 中的字符数组和字符串文字 [英] Comparing character arrays and string literals in C++

查看:30
本文介绍了比较 C++ 中的字符数组和字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符数组,我想弄清楚它是否与字符串文字匹配,例如:

I have a character array and I'm trying to figure out if it matches a string literal, for example:

char value[] = "yes";
if(value == "yes") {
   // code block
} else {
   // code block
}

这导致了以下错误:与字符串文字比较导致未指定的行为.我也尝试过类似的东西:

This resulted in the following error: comparison with string literal results in unspecified behavior. I also tried something like:

char value[] = "yes";
if(strcmp(value, "yes")) {
   // code block
} else {
   // code block
}

这没有产生任何编译器错误,但它的行为不符合预期.

This didn't yield any compiler errors but it is not behaving as expected.

推荐答案

std::strcmp 如果字符串相等则返回 0.

std::strcmp returns 0 if strings are equal.

这篇关于比较 C++ 中的字符数组和字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆