我在C语言的输出中获得未知字符

人气:356 发布:2022-10-16 标签: c c-strings reverse function-definition fgets

问题描述

我正在做这个练习:

编写一个程序,将句子中的单词颠倒过来,如下所示:我的名字是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:
");
    fgets(input,50,stdin);
    input[strcspn(input, "
")] = 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("
");
}

问题在于,输出结果给出了一个奇怪的字符,其中一些单词旁边有一个问号。例如:

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声明为Like

char output[50][50];

不包含字符串,因为您忘记在数组元素中的每个存储的字符序列后追加终止零字符''

但无论如何,您的方法都是不正确的,因为一个句子中的单词之间可以有多个空格字符,或者例如,一个句子可以从空格字符开始。

通常通过以下方式解决该任务。首先颠倒整个句子,然后依次颠倒句子中的每个单词。

这是一个演示程序。

#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] = '';
    
    printf( "Enter some words: " );
    
    fgets( input, N, stdin );
    input[ strcspn( input, "
" ) ] = '';     
    
    reverse_n( input, strlen( input ) );
    
    const char *separator = " 	";
    
    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

414