我正在尝试从 quiz_scores.txt 获取数据并打印到屏幕上,以便我可以将其扫描到数组中,但我不知道如何操作。我是否需要将文件硬编码到我的程序中?如果需要,如何进行?
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
int main(void)
{
//initializing variables
FILE *es;
FILE *hs;
int num=0;
int i;
int j;
int cols=10;
int rows=10;
int qid, s;
int quizarray[0][0];
int MAX_LENGTH=15;
char *result0;
char line[MAX_LENGTH];
FILE *qs="C:\\quiz_scores.txt";
qs = fopen("quiz_scores.txt", "r");
/*for (i=0; i<cols; i++){
for (j=0; j<rows; j++){
quizarray[i][j]=0;
fscanf(qs, "%d%d", quizarray[i][j]);
}
}
*/
while(fgets(line, MAX_LENGTH, qs))
{
printf("%s", line);
}
if(qs == NULL)
{
printf("Error: Could not open file\n");
return -1;
}
/*for (i=0;i<n;i++)
{
fprintf(qs, "%d\n");
}
fclose(qs);*/
return 0;
}
最佳答案
好吧,我想我知道你想要发生什么,将文件 quiz_scores.txt 中的数字读取到你的二维数组中并打印它们,对吗?我希望这些更正能让您做到这一点,并且您会理解为什么它以前不起作用。剩下的程序就由你自己完成了,祝你好运!!
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
int main(void)
{
//initializing variables
int num=0,i,j,cols=10,rows=10;//just smooshed all onto the same line cause it was annoying me
int quizarray[10][10];//You declared a 2d array with 0 elements(you wanted one with ten rows and columns I presume 10 teams 10 rounds)
FILE *qs = fopen("quiz_scores.txt", "r");//Your declaration of the file pointer was incorrect
if(qs == NULL)//This if needs to go before you read anything from the file otherwise its kind of redundant
{
printf("Error: Could not open file\n");
return -1;
}
for (i=0; i<cols; i++)
{
for (j=0; j<rows; j++)
{
quizarray[i][j]=0;
fscanf(qs,"%d", &quizarray[i][j]);//Them scanfs need &s mate
\\and don't try to scan in two integer into one array element
printf("%d",quizarray[i][j]);
if(j<rows-1)
printf("-");
}
printf("\n");
}
fclose(qs);//Dont comment fclose out bad things will happen :P
return 0;
}
关于c - 如何将文件打印到屏幕上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29856294/