+ 2

Hey ! Again don't know where the error is. HELP !!

#include <iostream> #include <string.h> using namespace std; int main() { string str , z; cin >> str ; int len =str.length(); for(int i= len ; i>=0 ; i--) z =z+str[i]; cout<<z; return 0; }

11th Jul 2021, 8:43 AM
Anjali Sharma
Anjali Sharma - avatar
4 Réponses
+ 6
Strings are zero-indexed, accessing the character at position str.length() is undefined behaviour. The last valid character is at position str.length() - 1, so that is where you need to start iterating. By the way, the <string.h> header is the old C header file for string functions. C++ uses <string> for std::string.
11th Jul 2021, 9:24 AM
Shadow
Shadow - avatar
+ 2
Works fine for me but since you haven't mentioned the actual error i am assuming you want to input multiple words but it only works for first word and so in order to get multiple words you will need to use getline function instead of cin. getline(cin,str);
11th Jul 2021, 8:56 AM
Abhay
Abhay - avatar
0
Try it now, it should work. There was some kind of glitch in SoloLearn.
11th Jul 2021, 9:22 AM
Solo
Solo - avatar
0
Thanks... It helps 😊
11th Jul 2021, 1:08 PM
Anjali Sharma
Anjali Sharma - avatar