gpt4 book ai didi

c - 不将成绩打印为二维数组

转载 作者:行者123 更新时间:2023-12-02 15:47:08 26 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void getGrades(FILE *ifp, int assigns, int stus, int grades[assigns][stus]);
void printGrades(int assigns, int stus, int grades[assigns][stus]);

int main(int argc, char *argv[])
{

int assigns = 0;
int stus = 0;
int grades[assigns][stus];

// command line arg. error checking
if (argc != 2)
{
printf("Syntax Error: ./<exec> <file>\n");
exit(1);
}
// file handle = open("infile.txt", read)
FILE *ifp = fopen(argv[1], "r");
if (ifp == NULL){
printf("Could not open %s for reading!\n", argv[1]);
exit(1);
}
fscanf(ifp, "%d%d", &assigns, &stus); // it does scan in 8 and 5 correctly
// print debugging check
// printf("assigns == %d\nstus == %d", assigns, stus);

getGrades(ifp, assigns, stus, grades);
printGrades(assigns, stus, grades);
return 0;
}

void getGrades(FILE *ifp, int assigns, int stus, int grades[assigns][stus])
{
int i = 0, j = 0;
// iterate through all of the rows & columns
for (i = 0; i < assigns; ++i){
for (j = 0; i < stus; ++j){
fscanf(ifp, "%d", &grades[i][j]);
}
}
}

void printGrades(int assigns, int stus, int grades[assigns][stus])
{
int i = 0, j = 0;
for (i = 0; i < assigns; ++i){
for (j = 0; j < stus; ++j){
printf("%10d", grades[i][j]);
}
printf("\n");
}
}

输入文件如下所示:

85个100 92 84 76 6899 91 83 75 6798 90 82 74 6697 89 81 73 6596 88 80 72 6495 87 79 71 6394 86 78 70 6293 85 77 69 0

我只是希望输出看起来像这样

   100        92        84        76        68
99 91 83 75 67
98 90 82 74 66
97 89 81 73 65
96 88 80 72 64
95 87 79 71 63
94 86 78 70 62
93 85 77 69 0

我不知道在我的程序代码中哪里出错导致不打印该输出。

大小是动态的,因为输入文件中的行和列可以改变。现在输入文件中的行是 8,列是 5。

最佳答案

您的代码的问题是:

    int assigns = 0;
int stus = 0;
int grades[assigns][stus];

这个数组的大小是多少?稍后您更改 assignsstus 的值,但此时数组已经创建。

你应该只在你有 assignsstus 的值后创建数组。如果将它向下移动到读取这些值的 fscanf 之后,它会起作用:https://onlinegdb.com/UIWe4ZZh5

关于c - 不将成绩打印为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73780953/

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