Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 比较字符数组不起作用_C++_Arrays_C Strings - Fatal编程技术网

C++ 比较字符数组不起作用

C++ 比较字符数组不起作用,c++,arrays,c-strings,C++,Arrays,C Strings,我在尝试在if条件下使用“字符数组”时发现了一个问题。我的输入应该是true,但事实并非如此 这是我的密码: #include <iostream> using namespace std; int main() { char a[20]; cin.get(a,15, '\n'); // for input cout << a << endl; // output if (a == "hello

我在尝试在
if
条件下使用“字符数组”时发现了一个问题。我的输入应该是
true
,但事实并非如此

这是我的密码:

#include <iostream>  
using namespace std;

int main()
{
    char a[20];
    cin.get(a,15, '\n');       // for input
    cout << a << endl;         // output
    if (a == "hello world") {  // checking if condition
       cout << "how are you?" << endl;
    }
}
#包括
使用名称空间std;
int main()
{
chara[20];
cin.get(a,15,'\n');//用于输入
cout您需要(包括标题
)来检查字符数组的相等性

试一试

STD::String ,这样你就可以很容易地做< /P>
std::string a;
getline( std::cin , a );
if(a=="hello world") //checking if condition
{
  std::cout<<"how are you";
}
std::字符串a;
getline(标准::cin,a);
if(a==“hello world”)//检查if条件
{

std::cout您应该使用
std::string
,而不是一些
char[]

然后,平等将如您所期望的那样发挥作用


这个
char[20]
strcmp
毫无意义,而且容易出错。这里没有它的位置。

这不是
if(strcmp(a,“hello world”)==0吗
要得到相同的结果吗?@nielsen,你没有仔细检查,仔细看,你会发现那里有一个
。@LightnessRacesinOrbit,我知道字符数组很容易出错,这就是为什么我还建议
std::string
@ShrawanBk,
cin
会跳过空格、换行等空格,所以空格以外的任何内容都会被删除如果使用简单的<代码> CIN <代码>,请不要使用。使用“代码> CIN。GETLIN(A,100)< /COD>。请不要在注释中张贴代码。请停止倾倒无意义代码。您的帖子非常难阅读。您能看到吗?为什么有那么多人仍然使用<代码> char []/CODE而不是<代码> STD::String C++?
std::string a;
getline( std::cin , a );
if(a=="hello world") //checking if condition
{
  std::cout<<"how are you";
}