Hello!
I want to make program which inverts the words in sentence, but not the sentence itself. For example, if I type "I love c plus plus." I program to print "I evol c suls .sulp".
My idea is to go throug the sentence (string) using for loop and look for a space position in it. When found, remebember its position and new for loop now should invert a word and put it in new string. So this would be the end for the first word. Now the first for loop must continue from space position+1 until second space found, an so on...
I have done this, but something's wrong here. I suppose the error is when writing the inverted word into a new char; it writes only spaces. Cannot figure how to solve this out. This is the code:
#include<iostream>
usingnamespace std;
int main() {
char sentence[51];
cout << "Type a sentence: ";
cin.getline(sentence,50);
int L=strlen(sentence);
int tmp;
char new_sentence[51];
for(int i=0; i<L; i++) { //Going through string
if(sentence[i]==' ') { //If space found
tmp=i; //Remember space position
for(int j=tmp-1; j>=0; j--) { //From space position-1, invert a word
new_sentence[j]=sentence[i]; //and write it into new char
i=tmp;
}
}
}
cout << "Output: " << new_sentence << endl;
system("pause");
return 0;
}
Define easy. I personally think it's pretty simple, but a beginner might have problems. I don't see how else than with the 3 steps I presented you it could be done, though of course the implementation of those steps may vary.
1) Store the words in an array/vector (I would go with vector), in order.
2) Go through each part of the array/vector one by one, and swap the letters in each word.
3) Output.