如何在 if/else 语句中组合字符串C++
How do I combine strings in an if/else statements in C++?
我是一个初学者学习C++,我对我在这里出错的地方感到困惑。到目前为止,我有下面的内容,但它没有识别 && 操作数。我会用什么来代替 &&?
我应该做的是编写一个程序,提示用户输入要混合的两种原色的名称。我将不胜感激任何和所有的建议。
谢谢。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
//Declare string variables for colors to mix
string color;
string color2;
string red;
string yellow;
string blue;
//Output instructions for creating secondary color
cout<< " Enter first primary color to help create a secondary color.";
cout<< " Must be in lowercase letters. "<<endl;
cin>>color;
cout<< "Enter another primary color to help create a secondary color: ";
cout<< " Must be in lowercase letters. "<<endl;
cin>>color2;
//Create statements to help determine the results
if (red && yellow)
{cout<< " Your secondary color is Orange! ";
}
else if (red && blue)
{cout<< " Your secondary color is Purple! ";
}
else if (blue && yellow)
{cout<< " Your secondary color is Green! ";
}
else
{cout<< "Input is inaccurate. Please enter a different color. ";
}
return 0;
}
if (red && yellow)
&&
询问每一方的评估结果是否为 true,如果是,则自身评估为 true。
这意味着您的代码询问变量red
的计算结果是否为 true,变量的计算结果yellow
是否为 true。
但那些是字符串!(还有空的!相反,您希望比较输入的字符串,并查看比较的计算结果是否为 true:
if (color1 == "red" && color2 == "yellow")
类似
if (color == "red" && color2 == "yellow")
变量的名称不是字符串。
当运算符的两端都是bool
对象或可以转换为bool
的对象时,运算符&&
有效。因此,这条线
if (red && yellow)
在语法上不正确。
可以使用以下命令在代码中正确表达您的意图:
if (color == "red" && color2 == "yellow" )
如果将变量的 vlaues 定义为 red
和 yellow
:
string red = "red";
string yellow = "yellow";
那么您也可以使用:
if (color == red && color2 == yellow )
相关文章:
- 组合字符串不适用于 libCurl,C++
- 如何组合一个宽字符字符串,中间插入一些空字符
- 从给定字符串中查找长度 k 的所有排列/组合
- 通过字符串迭代并将每个循环中的先前字符组合在一起
- 从左到右打印字符串的组合(不是排列)c++
- 在不使用递归的情况下求解所有 2D 字符串向量组合?(C++)
- 字符串向量的有效组合
- 将字符串转换为带有Isringstream的字符和INT(组合)
- Clang-Format:重新组合字符串文字
- 字符串二进制组合学
- 如何在 if/else 语句中组合字符串C++
- 我在 c++ 中组合了两个字符串,但放错了
- C Fstream字符串组合错误
- 如何使用for_each,transform,Iterator和lambda的某种组合将STD ::集合的字符串转换为小
- 在C++编程语言中,如何用n个向量长度的所有可能的字符串组合来填充向量
- 从字符串转换时,如何组合多个枚举
- C++组合两个以零结尾的字符串
- "无法封送'返回值':无效的托管/非托管类型组合",同时使用字符串数组封送委托
- 组合字符串 C++ 的映射和数组
- 如何组合C++字符串和Arduino字符串