如何比较用户输入(来自std::cin)与字符串

How to compare user input (from std::cin) to a string?

本文关键字:std 字符串 来自 cin 用户 何比较 比较 输入      更新时间:2023-10-16

所以这听起来很容易,但我得到一些奇怪的行为。

在我的程序中有以下代码:

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

  1. 您应该使用strcmpstrncmp来比较c风格字符串。ans != "global"只是比较指针指向的内存地址,而不是字符串的内容。

  2. 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") {......}

或者直接声明ansstd::string而不是char[]