如何比较用户输入(来自std::cin)与字符串
How to compare user input (from std::cin) to a string?
所以这听起来很容易,但我得到一些奇怪的行为。
在我的程序中有以下代码:
std::cout << "Would you like to generate a complexity graph or calculate global complexity? (graph/global)n";
char ans[6];
std::cin >> ans;
if (ans != "global") std::cout << ">>" << ans << "<<" << std::endl;
当我运行程序并在提示输入时输入"global"时,程序返回:
>>global<<
为什么if语句求值为true
-
您应该使用
strcmp
或strncmp
来比较c风格字符串。ans != "global"
只是比较指针指向的内存地址,而不是字符串的内容。 -
char ans[6];
应该是char ans[7];
,对于"global"
,您需要为终止空字符' '
多一个char
。
您应该使用std::string
,以避免此类问题。
您声明ans
为char数组,因此如果if (ans != "global")
表达式,ans
表示指向字符串开头的指针。所以你比较两个指针,它们显然不相等,你的表达式求值为真。如果你仍然想将ans
声明为c风格的字符串,你可以在比较之前从它构造一个std::string
:
if (std::string(ans) != "global") {......}
或者直接声明ans
为std::string
而不是char[]
。
相关文章:
- 我可以重新分配/覆盖std::字符串吗
- 如何将这个std::字符串转换为std::基本字符串
- std::字符串与 PCWSTR 的对话
- 重载 std::字符串运算符+ 用于打印枚举名称
- 从std::字符串创建OssBitString
- std::字符串擦除以删除最后一个字母
- 如何使用 C++ 中的原语初始化类(如 std::字符串从 const char* 初始化)
- std::字符串串联操作
- 如何有效地将一个大std::字符串的一部分转换为float
- 转义std::字符串中的特殊字符
- 用C++替换std::字符串中的一个子字符串,但不能全部替换
- C++std::字符串流到常量字符*的转换
- 如何将std::字符串转换为不同的字符串类
- 对齐C++字符串类型问题 std::字符串到 TStr
- std::字符串到字符*而不切割字节
- 编写具有非ASCII数据的std ::字符串
- 将 Delphi 的字符串转换为 std::字符串用于C++
- std::字符串添加到字符*
- 字符* 和 std::字符串和常量字符*之间的转换
- 用指针访问std ::字符串中的元素