c# 你能解释一下这个函数的作用吗?

iq0todco  于 2022-12-09  发布在  C#
关注(0)|答案(1)|浏览(186)

有人能解释一下这个函数是做什么的吗?有没有可能更有效地编写它?我不明白,尤其是if测试。
我所看到的:它只从文本文件中加载数字,这些数字存储到数组的指针中

void LoadNumbers(int*pNumberArray,FILE*textFile) //---F7-
{
    int i = 0;
    while (fscanf(textFile,"%d", &pNumberArray[i]) != EOF)
          {
          if (fscanf(textFile,"%*[^-+0-9]", &pNumberArray[i]) == EOF) break;
          else if (pNumberArray[i] != 0 ){++i; pNumberArray[i] = '\0';
          }    
}
tvz2xvvm

tvz2xvvm1#

LoadNumbers() zero or more integers from textFile into pNumberArray . 0 values are skipped. It appears the input file consist of an integer followed by something that is not +, - or a number. Upon exit the last element or two are 0 aka '\0'.
You could read both numbers with one fscanf() and you could deal with the terminating 0 after the loop. Alternatively, the function could return how many values are read instead of relying on 0 as the sentinel.

void LoadNumbers(int *pNumberArray, FILE *textFile) {
    int i = 0;
    for(;;) {
        int rv = fscanf(textFile,"%d%*[^-+0-9]", &pNumberArray[i]);
        if(rv == EOF) break;
        if(rv != 1) break; // ?
        if(pNumberArray[i]) i++;
    }
    if(i > 0 && !pNumberArray[i-1])
        pNumberArray[i] = 0;
}

int main(void) {
    FILE *f = fopen("1.txt", "r");
    if(!f) {
        printf("fopen failed\n");
        return 1;
    }

    int a[100];
    LoadNumbers(&a[0], f);
    for(int i = 0; a[i]; i++) {
        printf("%d\n", a[i]);
    }
}

With the example 1.txt input file:

0 a
1 b
0 c
2 d
3 e
4 f
0 g

Both the original and the revised function returns:

1
2
3
4

相关问题