-3

I want to concat two strings from the user's keyboard input, and this is the code I tried :

char a[50], b[50], aAndB[100];
printf("\na : ");
fgets(a, sizeof(a), stdin);
printf("\nb : ");
fgets(b, sizeof(b), stdin);
snprintf(aAndB, sizeof(aAndB), "%s/%s", a, b);
printf(aAndB);

The problem is that the two strings are concatenated with a "\n", to be more clear, this is the output :

a : text1
b : text2
text1
/text2

but the output I'm expecting is :

a : text1
b : text2
text1/text2

How can I solve this problem ?

4

2 回答 2

0

您可以通过在 snprintf() 行之前添加它来设置删除字符串 a 中的换行符。

a[strlen(a)-1] = '\0';
于 2013-09-29T03:09:44.467 回答
0

是的,fgets 会读回车,你可以使用 scanf 代替,或者手动将最后一个字符更改为 0,例如:a[strlen(a)]='\0';

于 2013-09-29T03:10:07.597 回答