Word Reverse in C++. What to use?

I was given a program to think about:
To read in a 4 word sentence from the keyboard then display it backwards (in terms of the words, not the letters)

I thought an array would be the most effective method so i could decrement the index to reverse, but doing that would cause my letters to be reversed not my words
My next idea was to read each word into a variable, but i do not know how to read in and skip the white space to get to the next word
Another idea was a for loop with a counter initialized at 0 and increment no larger than 3, but then my loop is infinite.
Any ideas?

I had one, its not complete but it is a work in progress

//read in sentence
cout << "Enter a 4 word sentence: ";

while (word_count !=4)
{
if (word_count < 4)
cout << "Sentence is too small";

else(word_count > 4)
cout<< "Sentence is too large";
}

if (word_count == 4)
{

}

Im pretty much stuck b/c every idea i have has a problem.
My main concern is reading in the words one by one or into an array that will allow me to reverse the words only

Experience: Some C++ (for/while loops, arrays(char), struct, str)
I think your second idea is best. You'll need a two-dimensional array of char:
1
2
3
// four words of max 29 characters + null
// (longest word in English: antidisestablishmentarianism)
char words[ 4 ][ 30 ];


Since a single word will not have whitespace, you can use std::isspace() (#include <cctype>) to know when to stop reading characters into the current word.

Read one character at a time:
char c = cin.get();

Hope this helps.
Last edited on
thank you it was helpful, but im a tad bit slow when it comes to this.
So
my array words [words][characters per word]; correct?

so when i read in input from keyboard read in character by character?
cout <<"Enter 4 word sentence";

char c;

for(m=1; m<=4; m++)
{
word[m] = ?

}//end for

then to reverse i would
cout << m[3] << m[2], etc?
Yep. You got it exactly!

;-)

[edit] You'll need another loop where ? is to read the letters of each word.

[edit2] BTW, please don't spam multiple forums with the same question. Would you mind deleting the extraneous post in the General C++ forum (before someone unwittingly replies to it)?
Last edited on
Topic archived. No new replies allowed.