如何使用C 随机显示用户输入字符串
How to randomly display an user input string using c++?
我正在尝试使用C 随机显示用户输入字符串,但我找不到方法。 目前,我正在定义一些字符串
#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
const string wordlist[4] = {"hi","hello","what's up","wassup"};
string word = wordlist [rand()%4];
cout<<word;
return 0;
}
我想要的是: - 我不想预先定义它们。我希望用户输入4个单词,并且我将显示一个用户给出的4个单词(随机)。
要做到这一点,您必须首先从 wordlist
array中删除 const
预选赛。
srand(time(0));
std::vector<string> wordlist(4);
for(auto& s: wordlist) std::cin>>s;
string word = wordlist [rand()%4];
cout<<word;
第3行是基于循环的C 11的范围,这样,我可以轻松地循环无需索引的
std::vector<string>
元素。如果字符串中有多个单词,则应相应地使用
getline(cin,s)
。然后在新行中输入每个字符串。但是,在混合cin
和getline
进行输入时要小心。- 如果要修复大小(即4),则可以使用
std::array
。
相关文章:
- C++如何通过用户输入删除列表元素
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 打印时有二叉树问题.用户输入不打印任何内容
- C ++奇怪的数组由用户输入
- 如何允许大写和小写用户输入?
- C++读取用户输入而不按回车键(Mac OS X),与Turbo Pascal中的读取键相同
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- 如何使用用户输入变量制作二维数组?
- 用户输入字符串的文件附加问题..C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?