[英]How to change newline character with one space when concatenating strings in C?
Firstly, i must mention that i'm just learning about strings in C as a beginner.首先,我必须提到,我只是作为初学者学习 C 中的字符串。 What i want to do is get 2 strings as input from an user and concatenate them.我想要做的是从用户那里获取 2 个字符串作为输入并将它们连接起来。 So here's what i did:所以这就是我所做的:
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);
The problem is that fgets also reads the newline character when the user inputs the first string so the output looks like this:问题是当用户输入第一个字符串时 fgets 也会读取换行符,因此 output 看起来像这样:
Hello World
I tried to use puts
instead of fgets and it worked well, but too many people said NOT to use that function.我尝试使用puts
而不是fgets并且效果很好,但是太多人说不要使用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.然后我发现我可以在第一个fgets
之后使用strcspn
删除换行符,但这并没有给我想要的单词之间的一个空格。 Desired output: Hello World
What i got: HelloWorld
所需的 output: Hello World
我得到了什么: HelloWorld
Any suggestions how to do that?任何建议如何做到这一点?
You can do the following way你可以通过以下方式
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 );
provided that the firststring has enough space to append the string stored in the array secondstring.前提是 firststring 有足够的空间将 append 存储在数组 secondstring 中的字符串。
Here is a demonstrative program这是一个演示程序
#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;
}
Its output might look like它的 output 可能看起来像
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从调用fgets
输入的字符串中删除换行符的一般方法如下
string[ strcspn( string, "\n" ) ] = '\0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.