如何在字符串数组中使用if语句
How to use an if statement in a string array?
下面的代码应该从数组中随机选择一个字符串,然后在Happy被选中时说"Yay!"
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
using namespace std;
int main()
{
srand(time(NULL));
string textArray[4] = { "Happy", "Sad", "Mad", "Overjoyed." };
int RandIndex = rand() % 4;
cout << textArray[RandIndex] << endl;
//if (textArray == "Happy") old
if (RandIndex == 0) //new
{
cout << "Yay!" << endl;
}
cin.get();
}
我的问题是操作数类型与字符串和字符不兼容。这个问题的最佳解决方案是什么?
编辑:所有我需要做的是替换"if (textArray == "Happy")"与"if (RandIndex == 0)"例如
if ( textArray[RandIndex] == "Happy" )
{
cout << "Yay!" << endl;
}
或
if ( RandIndex == 0 )
{
cout << "Yay!" << endl;
}
最好至少写成
string textArray[] = { "Happy", "Sad", "Mad", "Overjoyed." };
const size_t N = sizeof( textArray ) / sizeof( *textArray );
size_t randIndex = rand() % N;
相关文章:
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- c++:定义if语句中的模板
- C++嵌套的 If 语句中,它无法按预期工作
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 需要有关此 if 语句的帮助
- 转换器练习:跳过 if 语句和 if 语句
- 避免在 C++ 中的 if 语句中递增
- 如果仍然不满足要求,如何使 if 语句重复?
- do while 循环中的 if 语句以 yes 或 no 结尾
- 为什么在此C++代码中触发此 if 语句?
- 如何基于平台在制作文件中制作if语句?
- 在 if 语句中使用 GetKeyState 时,它会跳过条件
- C++ If 语句,从其他语句重复