c++ - 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();
}
例子:
其中哪个国家位于亚洲
- 泰国 2. 德国 3. 西班牙 4. 意大利
解决方案
这是类似于您的原始代码的工作代码,但使用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();
}
}
推荐阅读
- jquery - div外可拖动和排序
- python-2.7 - 你如何在 2.7 python input() 中得到一个 shell
- javascript - 如何在 fullcalendar-v4 中向事件添加文本
- python - 期望值:第 1 行第 1 列(字符 0) - Python
- amazon-web-services - AWS eb init not a valid key=value pair (missing equal-sign)
- elasticsearch - Elasticsearch - 按函数 min 和 max 舍入数字
- ruby-on-rails - 设计和看守 failure_app 未重定向到自定义路径
- python - 使用python从json文件中删除引号
- docker - 如何将多个 docker 容器的日志发送和聚合到日志?
- maven - 在“mvn test”运行中禁用硒测试