在C中串联字符串时,如何用一个空格更改换行符?

首先,我必须提到,作为一个初学者,我只是在学习C语言中的字符串。 我想要做的是从用户那里获取2个字符串作为输入并将它们连接起来。所以这就是我所做的:

char firststring[40], secondstring[40];

printf ("Enter first string: ");
fgets (firststring, 40, stdin);
printf ("Enter second string: ");
fgets (secondstring, 40, stdin);

strcat(firststring, secondstring);
printf("%s", firststring);

问题是,当用户输入第一个字符串时,fgets也会读取换行符,因此输出如下所示:

Hello World

I tried to use puts instead of fgets and it worked well, but too many people said NOT to use that function. Then i found out that i can use strcspn after the first fgets to remove the newline character, but that didn't gave me the one space i want between the words. Desired output: Hello World What i got: HelloWorld

有什么建议怎么做?

评论
  • nquas
    nquas 回复

    您可以按照以下方式进行

    printf ("Enter first string: ");
    fgets (firststring, 40, stdin);
    printf ("Enter second string: ");
    fgets (secondstring, 40, stdin);
    
    size_t n = strcspn( firststring, "\n" );
    firststring[n] = ' ';
    strcpy( firststring + n + 1, secondstring );
    

    只要firststring有足够的空间来附加存储在secondstring数组中的字符串。

    这是一个示范节目

    #include <stdio.h>
    #include <string.h>
    
    int main(void) 
    {
        enum { N = 40 };
        char firststring[N], secondstring[N];
    
        printf( "Enter first string: " );
        fgets( firststring, N, stdin );
    
        printf( "Enter second string: " );
        fgets( secondstring, N, stdin );
    
        size_t n = strcspn( firststring, "\n" );
        firststring[n] = ' ';
    
        strcpy( firststring + n + 1, secondstring );
    
        puts( firststring );
    
        return 0;
    }
    

    它的输出可能看起来像

    Enter first string: Hello
    Enter second string: World!
    Hello World!
    

    A general approach to remove the new line character from a string entered by a call of fgets is the following

    string[ strcspn( string, "\n" ) ] = '\0';