gpt4 book ai didi

c - 句子倒转功能

转载 作者:太空宇宙 更新时间:2023-11-04 02:43:14 25 4
gpt4 key购买 nike

包含 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

既然字符串 temp1temp2 最终都会得到一个 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;
}

关于c - 句子倒转功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29842588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com