gpt4 book ai didi

c - 显示输入文件中的项目

转载 作者:行者123 更新时间:2023-11-30 16:54:59 26 4
gpt4 key购买 nike

该程序扫描输入文件中的数字。

在这种情况下,数字是: 23 第353章 626 5 14 25 86 95 44 47 55 26 30 14 12 25 28 47 895 4255

用户可以选择显示任意数量的数字。

如果用户想要显示前 3 个数字,则应显示 23、353 和 626。

以下代码不显示数字。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>

void FillArray(FILE *fp, int n, int num[]);

int main()
{
FILE *fptr;
FILE *outPtr;

int num[20];
int i;
int number = 0;
int sum = 0;

fptr = fopen("numInput.txt", "r");

FillArray(fptr, number, num);

for (i = 0; i < number; i++)
{
printf("%d\n", num[i]);
}

for (i = 0; i < number; i++)
{
sum = sum + num[i];
}
outPtr = fopen("resOut.txt", "w");
fprintf(outPtr, "The Sum is %d", sum);

fclose(fptr);
fclose(outPtr);

return 0;
}

void FillArray(FILE *fp, int n, int num[])
{
int count = 0;
printf("How many number? ");
scanf("%d", &n);

for (count = 0; count < n; count++)
{
fscanf(fp, "%d", &num[count]);
}

}

最佳答案

比较(在您的代码中):

int number = 0;

与(由我评论)

FillArray(fptr, number, num);     /* FillArray() will receive only COPIES of arguments */

for (i = 0; i < number; i++)
{
printf("%d\n", num[i]);
}

这个循环体会执行多少次?

(提示:函数FillArray()没有机会改变number的值,所以它仍然是0。)

Recommended fixes (guaranteed) - based on using a pointer to number:

void FillArray(FILE *, int *, int *);        /* Insert explicit declaration in main() */
/* - only for my satisfaction ;-) */

FillArray(fptr, &number, num); /* &number instead of number */

void FillArray(FILE *fp, int *n, int num[]) /* *n instead of n */

scanf("%d", n); /* n instead of *n */

for (count = 0; count < *n; count++) /* *n instead of n */

(并考虑在提示中使用复数“多少数字?”)

关于c - 显示输入文件中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40434302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com