+ 2
Please can someone help me with my jungle camping code coach problem... I got 4 out of five test cases correct.
#include <iostream> using namespace std; int main() { int i; string lion, tiger, bird, snake; string sounds[3]; cin >> sounds[0]; cin >> sounds[1]; cin >> sounds[2]; cin >> sounds[3]; cin >> sounds[4]; cin >> sounds[5]; for ( i = 0; i <= 5; i++){ if(sounds[i] == "Grr"){ cout << "Lion "; } if(sounds[i] == "Rawr"){ cout << "Tiger "; } if(sounds[i] == "Ssss"){ cout << "Snake "; } if(sounds[i] == "Chirp"){ cout << "Bird "; } else if(sounds[i] == " "){ cout << ""; } } return 0; }
1 ответ
+ 1
----Errors in your code----
First of all, why do you only read 6 animal sounds? There could be n noises for all we know from the problem's description.
Second of all, why did you declare the sounds array which can hold 3 strings when you read 6 strings?
Third, strings lion, tiger, bird and snake are needless, just like the last else if in your code since it practically verifies if the string is composed of one space character which is impossible when you use cin >> .
----How to solve them?----
Since the given input is one string, it is recommended to use getline(cin, string) function for this problem so you can get the whole input even with spaces.
Use strcmp() function to compare strings char by char (if you compare them like normal values - string1 == string2 - it will only compare the number of characters those strings have) From now on, you'll have to use the sscanf function to read sound by sound from the input string or...
----How to optimize your solution----
We know the only sounds we can take as input are "Rawr, Grr, Ssss, Chirp", as you can see, all of these sounds have different starting characters, so you can use those characters to deduct which animal sound it is through indexes (String[i] ). When you're done with the comparison, you add the number of characters the word you've detected has (e.g. String[0] is C, so the sound is "Chirp" and you add 5 to i to skip them), but wait, there's the space character, because of that, you'll add Number Of Characters + 1 to i so you skip the space too.
Keep doing that while i is smaller than the input string's number of characters. How do you know how many characters the string has? With the Arr.size() function.
Oh and you should use switch() for comparison since it's more readable or if else if.
**SIDE NOTE : If you only wanna do this through strings and not mess up with indexes, I advise you to read into sscanf() function or trick the compiler with while (cin >> string) and use strcmp function.