- 1

What's problem in jungle camping?

#include <iostream> #include <string> #include <cctype> using namespace std; int main() { string s{}; getline(cin,s); size_t l=s.size(); for(size_t i{0};i<l;i++){ string dis{}; if(isalpha(s.at(i))) dis+=s.at(i); if(s.at(i)==' '||i==l-1){ if(dis.at(0)=='G') cout<<"Lion "; if(dis.at(0)=='R') cout<<"Tiger "; if(dis.at(0)=='S') cout<<"Snake "; if(dis.at(0)=='C') cout<<"Bird "; dis.erase(); } } return 0; }

4th Jun 2021, 3:09 AM
saurabh
saurabh - avatar
1 Resposta
+ 2
Your `dis` variable gets deleted at the end of each iteration of the for-loop. As a result, when s.at(i) is a space or the end of input is reached, `dis` is empty (as isalpha(a.at(i)) was false). Then when you try to access the 0th index (dis.at(0)), a runtime error is thrown as `dis` is empty. The fix is simple. Move the declaration of the `dis` variable outside the for-loop. Also, your code is unnecessarily long. First lf all, why even make `dis` a string when you're only reading the forst character? Just make it a char variable and reassign it each time. Even if `dis` is a string, why add to it and later erase it? Just reassign. The whole code could be much shorter if you simply use cin instead of getline(). cin takes the input word by word, so you don't need perform those checks for space etc. This code solves the "Jungle Camping" problem, but looks much cleaner https://code.sololearn.com/cUwq0o9j0vNa/?ref=app
4th Jun 2021, 3:46 AM
XXX
XXX - avatar