gpt4 book ai didi

c - 如何在数组中使用 fprintf?

转载 作者:行者123 更新时间:2023-11-30 14:47:05 25 4
gpt4 key购买 nike

我需要一些帮助。我正在尝试将代码的输出写入文件中。但是,每当我尝试在数组中使用 fprintf 时,我都会遇到问题。该代码在没有 fprintf 语句的情况下正常工作,每行打印 5 个分数。添加后,似乎会继续增加数组?

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

void displayScore(int testScores[]);
FILE *fpOut;

int main(void) {

if (!(fpOut = fopen("csis.txt", "w"))) {
printf("csis.txt could not be opened for input.");
exit(1);
}

int testScores[] = { 90, 85, 100, 50, 50, 85, 60, 70, 55, 55, 80, 95, 70, 60, 95, 80, 100, 75, 70, 95, 90, 90, 70, 95, 50, 65, 85, 95, 100, 65 };

displayScore(testScores);

fclose(fpOut);
system("pause");
return 0;
}

void displayScore(int testScores[]) {
int i = 0;

/*Prints 5 scores every line*/
for (i = 0; i < 30; i++) {
printf("%d, ", testScores[i]);
fprintf(fpOut, "%d, ", testScores[i]);
printf("%5d, ", testScores[i += 1]);
fprintf(fpOut, "%5d, ", testScores[i += 1]);
printf("%5d, ", testScores[i += 1]);
fprintf(fpOut, "%5d, ", testScores[i += 1]);
printf("%5d, ", testScores[i += 1]);
fprintf(fpOut, "%5d, ", testScores[i += 1]);
printf("%5d, \n", testScores[i += 1]);
fprintf(fpOut, "%5d, \n", testScores[i += 1]);
}
return;
}

最佳答案

正如已经指出的,与

printf("%5d, ", testScores[i += 1]);
fprintf(fpOut, "%5d, ", testScores[i += 1]);

您正在将一个数字打印到stdout,并将下一个数字打印到文件。因此,每个备用数字最终都会出现在文件中,而其他数字将打印到 stdout

您可以将其修改为

printf("%5d, ", testScores[i]);
fprintf(fpOut, "%5d, ", testScores[i]);
i+=1;

即,仅在打印到 stdout 和文件后才增加 i

或者您可以使用后缀增量运算符,例如

printf("%5d, ", testScores[i]);
fprintf(fpOut, "%5d, ", testScores[i++]);

i++ 中,i 的值将递增,但表达式中将使用 i 的初始值。阅读 What is the difference between prefix and postfix operators? .

您可以让计算机用类似的东西来重复,而不是自己重复

for (i = 0; i < 30; i++) {
printf("%5d, ", testScores[i]);
fprintf(fpOut, "%5d, ", testScores[i]);
if((i+1)%5==0)
{
printf("\n");
fprintf(fpOut, "\n");
}

}

仅当 i+1 能被 5 整除时才打印换行符。

<小时/>

不鼓励使用system()。请参阅Why should the system() function be avoided in C and C++? .

关于c - 如何在数组中使用 fprintf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51627735/

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