【发布时间】:2021-12-15 11:05:06
【问题描述】:
我正在做这个练习:
编写一个程序来反转句子中的单词,如下所示:My name is John --> John is name My
我写了这个:
#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
我不知道为什么输出会显示这个奇怪的字符。这可能是一个愚蠢的问题,但我是初学者。
附:对不起我的英语不好。
【问题讨论】:
-
C 中的字符串末尾有一个零。您的代码会复制每个单词的字符,但不会将零放在单词的末尾。
-
添加到上一条评论。将此代码添加到
if块中以 NUL 终止每个单词output[word][character] = '\0';
标签: c reverse c-strings fgets function-definition