当我在Visual Studio code的Windows上用C++运行此代码时,它会出现故障



我想打印这段代码"在桌子上";如果我写";笔记本电脑";或"笔记本电脑";,但当我写其他东西时,它会打印出";在桌子上";。这是代码。。。(C++(

#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
using namespace std;
int main()
{
string object;
cout << "Hi, I am you stuff assistant. How can I help you? n";
cin >> object;
if (object == "Laptop", "laptop") {
cout << "nOn the table";
}
else {
cout << "Unknown";
}
return 0;
}

条件object == "Laptop", "laptop"表示"laptop""laptop"是一个字符数组,它将被转换为指向第一个元素的指针。它不会是nullptr,所以它将永远是真的。

此处使用的,逗号运算符。它

  1. 计算左手操作数并丢弃结果
  2. 对右侧操作数求值并返回结果

相反,您应该比较每个字符串。

此外,您应该添加#include <string>以使用std::string,并删除未使用的标头(尤其是非标准标头(的#include

#include <iostream>
#include <string>
using namespace std;
int main(){
string object;

cout<<"Hi, I am you stuff assistant. How can I help you? n";
cin>>object;
if(object == "Laptop" || object == "laptop"){
cout<<"nOn the table";
} else {
cout<<"Unknown";
}
return 0;
}

问题就在这里:

if(object == "Laptop", "laptop"){
cout<<"nOn the table";
}

在这里,您将得到,运算符的结果,所以此语句将始终为true。

最新更新