include stdio.h
include stdlib.h
include string.h
#include <conio.h>
#define SIZE 40
int main( void )
{
char str[ SIZE ];
char strrev[ SIZE ];
char *temp1;
char *temp2;
int turn = 0;
printf( "Enter line of text: " );
fgets( str, SIZE - 1, stdin );
temp1 = strtok( str, " " );
temp2 = strtok( NULL, " " );
strcat( strrev, temp2 );
strcat( strrev, temp1 );
The problem is the condition inside while:
while( temp1 != NULL && temp2 != NULL ){
if( turn == 0 ){
temp1 = strtok( NULL, " " );
strcat( strrev, temp1 );
strcat( strrev, temp2 );
turn = 1;
}//end if
else{
temp2 = strtok( NULL, " " );
strcat( strrev,temp2 );
strcat( strrev, temp1 );
turn = 0;
}//end else
}//end while
printf( "\nThe reversed sentence is: %s", strrev );
getche();
return 0;
}//end function main
Since eventually either of the strings temp1 or temp2 are going to get a NULL why doesn't the loop function correctly ?
strcatting twice for each token you etract. Your target buffer might overflow. Also, forstrcatto work, you must begin with a null-terminated string. In your codestrrevisn't initialised. - M Oehm