#include <iostream>
usingnamespace std;
int main() {
string name;
string reverse;
cout<< "Type string to be reversed : "<<endl;
getline(cin, name);
for ( int i=0; i< name.length(); i++){
reverse = name[i]+ reverse;
}
cout<< reverse<<endl;
}
I'm trying to reverse a string including spaces. However, my program reverse each string individually. For example, I would like to reverse "This is a coding test". Reverse string : "test coding a is This".
My program does the following :
Type string to be reversed :
"this is a coding test"
"tset gnidoc a si siht"
It does reverse, but it reverses each word in my sentence.
Line 13 - 17: As long as the iostate of ss is "good" (It also means the input stream has not reached End of File). Each string will be extracted from it and stored in eachWord variable until the end of file is reached. Of course, eachWord will be added to reverse variable in the reverse order. http://www.cplusplus.com/reference/ios/ios/good/
Because of reverse = eachWord + " " + reverse; statement, the reverse variable will have an extra space at the beginning. So, line 20 removes that extra space before printing the result.
No, you are not. A string is a list of characters. You do successfully reverse the list, but that is not what you do want.
You want to take a list of words and reverse that list. The words are initially embedded in one string.
The std::cin is an input stream object. You can read from it. The data comes from "outside".
The ss is an input stream object. You can read from it. The data comes from string 'name'.
The istringstream makes it possible to use formatted input stream operations for reading one word at a time.
You could read word at a time from std::cin too, but then the "end of input" becomes different.
As an alternative, you may also want to have a look at this function: http://www.cplusplus.com/reference/cstring/strtok/
It splits a string into two pieces based on a specific character, for example the space. In your case you would just have to do it until you reach the end of the string.
To turn the order of the words around, you would have to start printing at the end of the array and reverse to the start of it, this could easily be done by moving the print line in the example to a separate function and using recursion.
Here is another solution, I reverse the entire string to start with, then extract words and reverse them back to normal, also the spaces are accounted for so if you wrote a few spaces after a word that would be mirrored.