我尝试使用此代码来读取名为packet的结构,其中包括priority(int),qty(float)和message(一个句子)。
for(i = 0; i < 3; i++) {
scanf("%d%f", &packet[i].priority, &packet[i].qty);
gets(packet[i].message);
printf("\n%d %.6f ", packet[i].priority, packet[i].qty);
printf("%s\n", packet[i].message);
}
问题在于我希望它能打印出类似的内容:
1 1 MESSAGE NUMBER ONE
2 1 MESSAGE NUM TWO
3 4 MESS NO THREE
但相反它打印
1 1
0 0 MESSAGE NUMBER ONE
2 1
就像gets()不需要在需要时执行,而是延迟&#34; for&#34;一步到位。有什么想法吗?
答案 0 :(得分:0)
要进行调试,我建议您在printf输出中包含单引号。你有足够的scanf,gets和printf组合语句,它们在输入和输出中的起始位置并不总是很清楚(正如你在问题中所示)。
printf("\n(d %d) (f %.6f) (s %s)\n, packet[i].priority, packet[i].qty, packet[i].message);
可以帮助您确定正在打印的内容,以及输出可能很容易看起来的位置
(d 0) (f 0) (s
)
如果没有多余的字符,您很容易将新行输出混淆为位置非常接近的输入例程中的错误。
答案 1 :(得分:0)
试试这个
scanf("%d%f %[^\n]", &packet[i].priority, &packet[i].qty,
packet[i].message);
printf("\n%d %.6f ", packet[i].priority, packet[i].qty);
printf("%s\n", packet[i].message);
答案 2 :(得分:0)
首先:Why is the gets function so dangerous that it should not be used?这应该在使用获取时清除一些混乱,以及为什么不应该使用它。
scanf
将在输入缓冲区中留下行终止符\n\r
,因此当您开始使用gets()
时,它将获取行终止符。所以回顾一下,for循环没有'延迟'gets()
正在消耗行终止符,并且只要它发生就会拾取下一行并将其分配给message
。
您可以尝试将message
定义为要读入的字符数组。
struct placeholder
{
char message[25]; // Able to hold a message of length 24.
// rest of your struct variables.
}PlaceHolder;
// using scanf is still appropriate for reading in the message
要阅读消息,您需要使用换行符 - 请查看此内容以获取更多帮助:scanf: "%[^\n]" skips the 2nd input but " %[^\n]" does not. why?