Using if
and while
/do
-while
, my job is to print following user's inputs (string value) in reverse order.
For example:
input string value : "You are American" output in reverse order : "American are You"
Is there any way to do this?
I have tried
string a;
cout << "enter a string: ";
getline(cin, a);
a = string ( a.rbegin(), a.rend() );
cout << a << endl;
return 0;
...but this would reverse the order of the words and spelling while spelling is not what I'm going for.
I also should be adding in if
and while
statements but do not have a clue how.
This uses exactly one each of
if
andwhile
.The algorithm is:
You might try this solution in getting a
vector
ofstring
's using the ' ' (single space) character as a delimiter.The next step would be to iterate over this vector backwards to generate the reverse string.
Here's what it might look like (
split
is the string splitting function from that post):Edit 2: If you don't like
vector
s for whatever reason, you can use arrays (note that pointers can act as arrays). This example allocates a fixed size array on the heap, you may want to change this to say, double the size when the current word amount has reached a certain value.Solution using an
array
instead of avector
:Edit: Added includes,
main
function,while
loop formatThis code here uses string libraries to detect the blanks in the input stream and rewrite the output sentence accordingly
The algorithm is 1. Get the input stream using getline function to capture the spacecs. Initialize pos1 to zero. 2. Look for the first space in the input stream 3. If no space is found, the input stream is the output 4. Else, get the position of the first blank after pos1, i.e. pos2. 5. Save the sub-string bewteen pos1 and pos2 at the beginning of the output sentence; newSentence. 6. Pos1 is now at the first char after the blank. 7. Repeat 4, 5 and 6 untill no spaces left. 8. Add the last sub-string to at the beginning of the newSentence. –
This example unpacks the input string one word at a time, and builds an output string by concatenating in reverse order. `
`
Here is a C-based approach that will compile with a C++ compiler, which uses the stack to minimize creation of
char *
strings. With minimal work, this can be adapted to use C++ classes, as well as trivially replacing the variousfor
loops with ado-while
orwhile
block.To compile with a C++ compiler, and then use: