首页 > 解决方案 > c++ 带打印的字符串生成器(cout)

问题描述

所以我想用 C++ 做一个小测验,但它不起作用,这是我尝试过的代码

static const char alphanum[] =

"which one of this cities located in france"

cout << "1. paris   2. singapore   3. dubai    4. thailand";

"which one of this countries located in asia"

cout << "1. thailand   2. germany   3. spain    4. italy";

int stringLength = sizeof(alphanum) - 1;

char genRandom()  // Random string generator function.
{

    return alphanum[rand() % stringLength];

}

int main()

{

    srand(time(0));

    for(int z=0; z < 1; z++)

    {

        cout << genRandom();

    }

例子:

其中哪个国家位于亚洲

  1. 泰国 2. 德国 3. 西班牙 4. 意大利

标签: c++stringrandom

解决方案


这是类似于您的原始代码的工作代码,但使用std::string而不是char*. 您的代码有很多问题,因此我不会解释它们,我只是建议您阅读一本关于 C++ 的好书

#include <string>
#include <iostream>
using namespace std;

static const string alphanum[] ={
"which one of this cities located in france \n1. paris   2. singapore   3. dubai    4. thailand",
"which one of this countries located in asia\n1. thailand   2. germany   3. spain    4. italy"
};

const int stringLength = sizeof(alphanum)/sizeof( *alphanum);

const string& genRandom()  // Random string generator function.
{
    return alphanum[rand() % stringLength];
}

int main()
{
    srand(time(0));

    for(int z=0; z < 1; z++)
    {
        cout << genRandom();
    }
}

推荐阅读