如何在字符串数组中使用if语句

How to use an if statement in a string array?

本文关键字:if 语句 数组 字符串      更新时间:2023-10-16

下面的代码应该从数组中随机选择一个字符串,然后在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;