【发布时间】:2017-03-11 02:47:11
【问题描述】:
我正在尝试编写一个程序,该程序需要用户输入两次,然后将结果连接起来,但我遇到了问题。
我的预期输出是:
What would you like your message to be? input
message received: input
What would you like your message to be? words
message received: words
new message: inputwords
相反,我收到了一个乱码。
收到的输出:
What would you like your message to be? input
message received: input
What would you like your second message to be? words
message received: words
new message: ??s?inputwords
第一个问题:
如何正确连接这两个字符串?
另外:
由于我只接受每条消息的 5 个字符的输入,我将如何在这些 fgets 调用之间清除缓冲区中的剩余元素而不将剩余元素读入“垃圾”数组?
这是我正在使用的代码:
#include <stdio.h>
#include <string.h>
int main() {
char message[6];
char garbage[9999];
char message2[6];
printf("\nWhat would you like your message to be? ");
fgets(message, 6, stdin);
printf("message received: %s\n", message);
fgets(garbage, 9999, stdin); //this is gross
printf("\nWhat would you like your second message to be? ");
fgets(message2, 6, stdin);
printf("message received: %s\n", message2);
fgets(garbage, 9999, stdin); //still gross
char newString[25];
strcat(newString, message);
strcat(newString, message2);
printf("new message: %s\n", newString);
return 0;
}
注意:我知道我应该获取 fgets 的返回值,为简洁起见,我将其省略了。
【问题讨论】:
-
strcat将一个字符串附加到另一个字符串。但是您使用未初始化的参数缓冲区调用它。
标签: c undefined-behavior fgets strcat