<分区>
我一直在尝试在 C 中创建一个函数,该函数读取 double 值,然后将其存储到数组中。我希望能够返回数组的大小,以便我可以在 main 中使用它。所以这个函数的目的是要求用户将值输入到数组中并键入 ^d (ctrl+d) 或 EOF 以结束循环。
#include <stdio.h>
//Prototype Declaration
int getdata(double[], int);
int main(int argc, char* argv[]) {
double array[20];
int count = 0, max = 20;
//Calls the getdata function
count = getdata(array, max);
printf("%s%lf%s","Array1: " ,array[1], "\n");
printf("%s%d%s", "Count is: ", count, "\n");
return 0;
}
-----(我正在链接模块,所以它们在不同的文件中)--------
#include <stdio.h>
//Define getdata.c
int getdata(double values[], int limit){
printf("%s","Please enter your values into the array.\n");
int count = 0;
double n;
while ((count < limit) && (scanf("%lf",&n) != EOF)) {
values[count] = n;
count++;
}
return count;
}
但是,如果我提前中断循环,数组值会正常传递,但计数只会打印出 20。我假设程序会自动用一些东西填充其余的空索引,并且在我输入 EOF 后继续增加计数值。我该怎么做才能使程序正确获取输入的值的数量?我用 C 编写的代码不多。我主要用 C++ 完成我的工作。我熟悉通过引用传递但使用 C。