如何使用C 随机显示用户输入字符串

How to randomly display an user input string using c++?

本文关键字:用户 输入 字符串 显示 随机 何使用      更新时间:2023-10-16

我正在尝试使用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)。然后在新行中输入每个字符串。但是,在混合cingetline进行输入时要小心。

  • 如果要修复大小(即4),则可以使用std::array