包含 stdio.h
包含标准库.h
包含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 );
问题是 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
既然字符串 temp1
或 temp2
最终都会得到一个 NULL
,为什么循环不能正常运行?
可以用递归来反转句子,用sscanf来分割字符串:
#include <stdio.h>
void recursive(const char *s)
{
char b[100];
int n;
if (sscanf(s, "%99s%n", b, &n) == 1)
recursive(s + n), printf(" %s", b);
}
int main()
{
recursive("foo bar baz");
return 0;
}
我是一名优秀的程序员,十分优秀!