简体   繁体   English

如何返回读取的数字或N的数量的计数,以数组中较小者为准?

[英]How to return a count of the number of numbers read or N, whichever is smaller in an array?

I'm confused about how the function below can be worked so that it can read the numbers from a data file, place the numbers in the array A and return a count of the number of numbers read or N, whichever is smaller. 我对下面的函数的工作方式感到困惑,以便它可以从数据文件中读取数字,将数字放置在数组A中,并返回读取的数字数或N(以较小者为准)的计数。

#include <stdio.h>
{
    int readNumbers(FILE* input,int A[],int N)
    int n;
    n = 0;
    while(n < N&&!feof(input))
    {
        fscanf_s(input,"%f",&A[n]));
        n++;
    }
}

The above program should read a file of numbers and place them into an array. 上面的程序应该读取一个数字文件,并将它们放入数组中。 I'm just stuck on how I would program in a count of the number of numbers read or N. 我只是停留在如何计算读取的数字或N的数量上。

1 Wrong scanf() usage 1错误的scanf()使用

int readNumbers(FILE* input,int A[],int N)
...
// fscanf_s(input,"%f",&A[n]));
fscanf_s(input, "%d", &A[n]));

2 Rather than using feof() incorrectly - it should be used after fscanf_s() return EOF to distinguish a feof() from ferror() . 2而不是错误地使用feof() ,它应该 fscanf_s()返回EOF 之后使用以区分feof()ferror()

while(n < N && fscanf_s(input,"%d", &A[n]) != EOF) {
  ...
}

3 As @Hogan says, add return n; 3如@Hogan所说,添加return n;

4 Syntax error: change 4语法错误:更改

{
int readNumbers(FILE* input,int A[],int N)
// to
int readNumbers(FILE* input,int A[],int N) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM