I am trying to write a function that reverses the words inside a string keeping spaces between the words. So, if the input is “abc def ghj” output should be “cba fed jhg”. It works when i put the string by hand into the function ReverseLettersDecode(“abc def ghj) for example. However, when i put the parameter of the function with a input it does not work. Example: ReverseLettersDecode(a) where a is input from the user. I am new to the language so please keep that in mind when explaining 🙂 thanks.
string reverseWord(const string& word){
string reverseword;
string temp;
int length = word.length();
for (int i = length-1; i > -1 ; i--){
temp = word.at(i);
reverseword += temp;
}
return reverseword;
}
string reverseLettersDecode(const string& message){
string reversedmsg;
string msg = message;
int index = msg.find(" ");
while (index != string::npos){
reversedmsg += reverseWord(msg.substr(0,index)) + " ";
msg = msg.substr(index+1);
if (msg.find(" ") == string::npos){
reversedmsg += reverseWord(msg);
break;
}
index = msg.find(" ");
}
return reversedmsg;
}
This is the code. The first function is for reversing a word and the one below is reversing a sentence with spaces using the first function.
4