我正在做这个练习:
编写一个程序,反转句子中的单词,如下所示:我的名字是约翰 --> 约翰的名字是我的
我写了这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int word=0,character=0;
char input[50];
char output[50][50];
int InLength;
printf("Enter some words:\n");
fgets(input,50,stdin);
input[strcspn(input, "\n")] = 0;
InLength=strlen(input);
for (int i=0;i<InLength;i++){
if (input[i]==' '){
character=0;
word++;
}
else{
output[word][character]=input[i];
character++;
}
}
for (word;word>=0;word--){
printf("%s ",output[word]);
}
printf("\n");
}
问题是输出给出了一个奇怪的字符,一些单词旁边有一个问号。例如:
Enter some words:
hello how are you
you���� are how hello
另一个例子:
Enter some words:
first second third hello good
good� hello�� third���� second first
我不知道为什么输出显示这些奇怪的字符。这可能是一个愚蠢的问题,但我是初学者。
附:对不起,我的英语不好。
数组的元素output
声明如下
char output[50][50];
不包含字符串,因为您忘记将数组元素中每个存储的字符序列附加到终止零字符'\0'
.
但无论如何,您的方法都是不正确的,因为句子中的单词之间可以有多个空格字符,或者例如句子可以从空格字符开始。
通常任务是通过以下方式解决的。首先将整个句子颠倒过来,然后依次颠倒句子中的每个单词。
这是一个演示程序。
#include <stdio.h>
#include <string.h>
void reverse_n( char s[], size_t n )
{
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n-i-1];
s[n-i-1] = c;
}
}
int main(void)
{
enum { N = 100 };
char input[N];
input[0] = '\0';
printf( "Enter some words: " );
fgets( input, N, stdin );
input[ strcspn( input, "\n" ) ] = '\0';
reverse_n( input, strlen( input ) );
const char *separator = " \t";
for ( char *p = input; *p; )
{
p += strspn( p, separator );
char *q = p;
p += strcspn( p, separator );
reverse_n( q, p - q );
}
puts( input );
return 0;
}
程序输出可能类似于
Enter some words: My name is John
John is name My
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)