首先,我必须提到,作为一个初学者,我只是在学习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
有什么建议怎么做?
您可以按照以下方式进行
只要firststring有足够的空间来附加存储在secondstring数组中的字符串。
这是一个示范节目
它的输出可能看起来像
A general approach to remove the new line character from a string entered by a call of
fgets
is the following