【问题标题】:c++ string generator with print (cout)c++ 带打印的字符串生成器(cout)
【发布时间】:2021-10-12 02:26:53
【问题描述】:

所以我想用 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++,您应该使用std::string 而不是const char*。另一件需要注意的事情是有一个类似C 的字符串,你应该使用const char* array[],因为const char array[] 只声明一个字符数组而不是一个字符串数组。您也不需要数组声明中的cout &lt;&lt; "..."。但是,还有其他语法错误。你应该看看如何声明数组。

标签: c++ string random


【解决方案1】:

这是与您的原始代码类似的工作代码,但使用std::string 而不是char*。你的代码有很多问题,我就不解释了,我只推荐你看decent book about 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();
    }
}

【讨论】:

    猜你喜欢
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2020-11-08
    • 2013-03-13
    • 1970-01-01
    相关资源
    最近更新 更多