所以,我需要从一行读取多个数字(浮点)输入,每个输入由一个空格分隔,按Enter键完成。
These numeric inputs: 50 20 10 5 2 1 0.50 0.20 0.10
此外,在.c中我希望能够存储它们,对它们进行总结,按它们的值过滤它们(接受50s但过滤掉35s等)并能够将它们向上或向下舍入,能够区分多个相同值的输入..
这是我在C的前几周,所以我对所有库和控件都没有信心。到目前为止,我已经尝试了几种不同的方法,scanf到多个浮点数,scanf到数组,甚至给fgets,strtok和sscanf看了一些Q&在这里,但没有运气。一般来说,我正在寻找一种以简洁明了的方式执行此操作的方法。
(这是一个更大的学校项目的一部分,只是为了澄清我不是要求完成的解决方案或我可以复制的代码块,我将非常感谢更多的“正确方向的点”方法..)
编辑:使用回车确认输入后,这会导致分段错误。我知道这与内存有关,但不知道如何解决它..而且,我觉得使用pi作为空槽表示非常愚蠢,但我无法想出其他任何东西。我不知道将放入多少值,因为现在我将其限制为5用于测试目的。
#include "stdio.h"
#include "stdlib.h"
int main(){
int x=0, y=0;
float a[5] = {3.141592};
char buffer[5] = {3.141592};
printf("Input: ");
fgets(buffer, 5, stdin);
while(sscanf(buffer, "%f ", &a[x]) == 1 && !feof(stdin)){
sscanf(buffer, "%f ", &a[x]);
x++;
}
printf("Saved input: ");
while(y<=5 && a[y] != 3.141592){
printf("%.2f", a[y]);
y++;
}
printf("\n");
return 0;
}
答案 0 :(得分:0)
Assuming your input is 50 20 10 5 2 1 0.50 0.20 0.10
, this line:
fgets(buffer, 5, stdin);
will read 4 characters into buffer
(plus a NUL terminator), giving
buffer = { '5', '0', ' ', '2', '\0' }
// or equivalently
buffer = "50 2"
Then we enter this loop:
while(sscanf(buffer, "%f ", &a[x]) == 1 && !feof(stdin)){
The sscanf
call succeeds, placing 50.0
into a[0]
. feof(stdin)
is false because the previous read operation (fgets
) didn't reach the end of the input, so the second condition also succeeds.
sscanf(buffer, "%f ", &a[x]);
Here in the loop body we call sscanf
again, placing 50.0
into a[0]
again.
x++;
}
Then we increment x
(from 0 to 1) and restart the loop.
while(sscanf(buffer, "%f ", &a[x]) == 1 && !feof(stdin)){
The only thing that's changed is the value of x
, so this time around we place 50.0
in a[1]
and re-enter the loop body.
The loop body again overwrites a[1]
with the same value it just scanned (50.0
) and increments x
to 2.
Then we restart the loop and place 50.0
in a[2]
.
...
Then we restart the loop and place 50.0
in a[3]
.
...
Then we restart the loop and place 50.0
in a[4]
.
...
Then we restart the loop and place 50.0
in a[5]
.
...
Then we restart the loop and place 50.0
in a[6]
.
...
But wait! The last element of our array is a[4]
. We've just written to a[5]
and a[6]
, which don't exist. This is an infinite loop that keeps writing to ever-increasing indices of a
, going way out of bounds.