0

Add multiple Strings(words) into Array.

I want to input 4 Strings and put them inside the array of food. After this the programm should randomly select a dish for me to eat. #include <iostream> #include <string> #include <vector> using namespace std; int main() { srand(time(0)); vector <string> food; std::string input; std::string random; do { cin >> input; food.push_back(input); } while (food.size <= 4); for (int i=0;i < 1; i++) { random = food[rand() % 4]; cout << random << endl; } return 0; } This is the code but im not able to take multiple strings and store them inside one Array.

23rd Sep 2021, 8:13 PM
Ragnar Mxyzptlk
Ragnar Mxyzptlk - avatar
6 odpowiedzi
+ 3
Ragnar Mxyzptlk Are you using solo compiler? I mean did you try the code here? If it is, you should enter the food names one by one and after enter each one break a line, like: Food1 Food2 Food3 Food4 Submit Enter the food names as I wrote. Then submit. It works!
23rd Sep 2021, 8:43 PM
mesarthim
mesarthim - avatar
+ 5
Ragnar Mxyzptlk , i think it should be: ... while (food.size() <= 4); ...
23rd Sep 2021, 8:30 PM
Lothar
Lothar - avatar
+ 3
You should define a variable to take input as much as 4 and increment it until 4 input taken. So, try this. It works. #include <iostream> #include <string> #include <vector> using namespace std; int main() { srand(time(0)); vector <string> food; std::string input; std::string random; int k = 1; do { cin >> input; food.push_back(input); k++; } while (k <= 4); for (int i=0;i < 1; i++) { random = food[rand() % 4]; cout << random << endl; } return 0; }
23rd Sep 2021, 8:34 PM
mesarthim
mesarthim - avatar
+ 3
Ragnar Mxyzptlk Also, if you want to show to user that it must be enter a food each time, you add this line in the loop, cout << "Enter the " << k << ". name of food" ;
23rd Sep 2021, 8:47 PM
mesarthim
mesarthim - avatar
+ 2
Omg finally. It realy works!!! 🤣 Thank u very much! Crazy compiler...
23rd Sep 2021, 8:45 PM
Ragnar Mxyzptlk
Ragnar Mxyzptlk - avatar
+ 1
With both the Compiler error is gone. But still if i run the programm i can just type in 1 word, it does not ask me 3 more Times to input a string. And i dont get it, im working 3 days just for this problem :D
23rd Sep 2021, 8:39 PM
Ragnar Mxyzptlk
Ragnar Mxyzptlk - avatar