+ 1

Solved: Code Coach: Jungle Camping. I am stuck. The last result is wrong. Helpful for any advice.

#include <iostream> #include <vector> using namespace std; int main() { string animal1; string animal2; string animal3; string animal4; string animal5; cin >> animal1 >> animal2 >> animal3 >> animal4 >> animal5; vector<string> sounds{animal1, animal2, animal3, animal4, animal5}; vector<string> animals; int soundsTotal = sounds.size(); while (soundsTotal > 0) { for (const string &sound : sounds) { if (sound == "Rawr") { animals.push_back("Tiger"); } else if (sound == "Chirp") { animals.push_back("Bird"); }else if (sound == "Ssss"){ animals.push_back("Snake"); }else if (sound == "Grr"){ animals.push_back("Lion"); } soundsTotal--; // Decrement soundsTotal within the loop } } for (string animal : animals) { cout << animal << " "; } return 0; }

29th Dec 2023, 4:15 PM
Denis Durban
Denis Durban - avatar
6 Respostas
+ 2
12 is also not enough. You should find a way that does not require you to declare a separate variable for each input. You have already used vectors in your code (good idea), so for example: string input; vector<string> sounds; while (cin >> input) { sounds.push_back(input); }
29th Dec 2023, 11:21 PM
Tibor Santa
Tibor Santa - avatar
+ 1
How do you know how many sounds you will get? Maybe you should figure out how to handle more than 5.
29th Dec 2023, 4:54 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Tibor Santa Hello, Thanks for helping me. Are you sure that the problem is that my code can only handle 5 inputs? I tried 12 and the last is still wrong. Too bad I cannot see the reason why my code is wrong in the last test result.
29th Dec 2023, 9:51 PM
Denis Durban
Denis Durban - avatar
+ 1
Tibor Santa I tried something similar like you did, but I couldn't make it work. But your piece of code looks good and simple. Thanks a lot
30th Dec 2023, 12:32 AM
Denis Durban
Denis Durban - avatar
+ 1
Tibor Santa thanks again. It's solved :)
30th Dec 2023, 12:55 AM
Denis Durban
Denis Durban - avatar
0
Please, read the description for the task again, because then you will find out that there are only four noises and four animals, and since you are using C++, you could use a map to hold the key/value pairs for the sounds and animals. Your input will be noises so it would then be easy to pick them from a map what animal it is.
30th Dec 2023, 12:06 AM
Jan
Jan - avatar