Original Post
Ok.. well I am just trying to assist a friend with a program that reverses a sentence. I wrote the program and my test data was to enter ''Terry is a moron'' , this string returns
moron a is noromTerry
So.. I thought my program wasn''t behaving quite correctly.. so I tried with several sets of data including
Timmy is a moron, result:
moron a is noromTimmy
Bob is a moron, result:
moron a is Bob
I can''t work out why the strange behaviour, several other sentences worked fine.. why when 5 letters are used for the first word does it add the reversed moron on the end?
#include <iostream>
#include <stdlib.h>
#include <string.h>
char * reversestring(char*);
int main(int argc, char *argv[])
{
char *sentence = new char[255];
char *newsentence = new char[255];
char *wrd;
char *token = " ";
cout << "Enter a sentence: ";
cin.get(sentence,255);
sentence = reversestring(sentence);
cout << "Reversed Sentence: " << sentence << "\n";
wrd = strtok(sentence,token);
wrd = reversestring(wrd);
strcat(newsentence,wrd); //First word
while((wrd = strtok(NULL,token)))
{
wrd = reversestring(wrd);
strcat(newsentence," "); //Need a space
strcat(newsentence,wrd); //Add the word!
}
cout << "New Sentence: " << newsentence << "\n";
system("PAUSE");
delete newsentence;
delete sentence;
}
//Reverse a given string character by character
char * reversestring(char *strn)
{
char *mystr = new char[strlen(strn)];
char *cur;
int idx = strlen(strn) - 1;
int id2 = 0;
do
{
cur = &strn[idx];
mystr[id2++] = cur[0];
idx--;
}while(idx > -1);
return mystr;
}