-3

I am trying to randomly display a user input string using c++ but I couldn't find a way to do. Currently I am pre defining some strings

#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;
}

What I want is:- I don't want to pre define them. I want the user to type in 4 words and I will display a word from the 4 words given by the user (randomly).

Joy Dey
  • 37
  • 5

1 Answers1

0

To do that you will have to first remove const qualifier from wordlist array.

srand(time(0));
std::vector<string> wordlist(4);
for(auto& s: wordlist) std::cin>>s;
string word = wordlist [rand()%4];
cout<<word;
  • Line 3 is C++11's range based for loop, this way I can easily loop over elements of std::vector<string> without indices.

  • If there are multiple words in a string then use getline(cin,s) accordingly. Then input each string in a new line. But be careful when mixing cin and getline for taking input.

  • You can use std::array if the size is going to be fixed (i.e. 4) as mentioned in comments.
madhur4127
  • 276
  • 2
  • 13