当字符串是某个单词时给出输出?

Give an output when a string is a certain word?

本文关键字:输出 单词时 字符串      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main()
{
string n;
cout << "Enter the name of an automobile: " << endl;
cin >> n;
while( n != "End") {
if( n == ("Tesla" or "Volt" or "Leaf")) {
cout << "Electric" << endl;}
else {
if( n == ("Clarity" or "Mirai")){
cout << "Hydrogen Powered" << endl;}
else {
cout << "Gas Powered" << endl; }}
cout << "Enter the name of an automobile: " << endl;
cin >> n;
}
return 0;
}

它需要说明每辆车是如何供电的。基本上如果我输入"特斯拉",它应该说"电动";"福特"应该出现"汽油动力"。当我输入"结束"时,它就结束了。 我收到此错误 .cpp|16|错误:二进制表达式的操作数无效("std::__1::string"(又名"basic_string,分配器>"(和"布尔"(|

这应该有效!在C++没有or.使用||.此外,每次都需要将条件放在if中,例如if(n=="Tesla"||n=="Volt"||n=="Leaf")

#include <iostream>
using namespace std;
int main()
{
string n;
cout << "Enter the name of an automobile: " << endl;
cin >> n;
while( n != "End") {
if( n == "Tesla" || n== "Volt" ||n== "Leaf") {
cout << "Electric" << endl;}
else {
if( n == "Clarity" || n=="Mirai"){
cout << "Hydrogen Powered" << endl;}
else {
cout << "Gas Powered" << endl; }}
cout << "Enter the name of an automobile: " << endl;
cin >> n;
}
return 0;
}
if( n == ("Tesla" or "Volt" or "Leaf"))

需要更改为

if( (n == "Tesla") || (n == "Volt") || (n == "Leaf") )

在执行相同操作的其他地方进行类似的更改

  • C++中没有or关键字。您需要使用||
  • ("特斯拉||"伏特" ||"叶子"(将始终返回真。所以条件将变成 if (n == (true((,这永远不会为真。