c++ - Segmentation fault in reversing string program -
i trying reverse string. can explain me why giving me segmentation fault?
#include <iostream> #include <string> using namespace std; int main(){ string str,rstr; int len=str.length(),i=0; cin>>str; while(str[i]!='\0'){ rstr[--len]=str[i++]; } rstr[str.length()]='\0'; cout<<rstr; return 0; }
p.s.: need reverse without using library functions.
i want go way doing it, practice purposes, try changes , start there
#include <iostream> #include <string> using namespace std; int main(){ string str,rstr; cin>>str; // --- moved line rstr = str; // --- added line int len=str.length(),i=0; while(str[i]!='\0'){ rstr[--len]=str[i++]; } rstr[str.length()]='\0'; cout<<rstr; return 0; }
Comments
Post a Comment