【问题标题】:How do I get the file to print to the screen?如何让文件打印到屏幕上?
【发布时间】:2015-04-24 19:52:38
【问题描述】:

我正在尝试从 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;
}

【问题讨论】:

  • 如果您希望人们帮助您,您应该格式化并清理您的问题。
  • 我迷路了,我做不到。
  • 什么是文件内容?
  • 学生证号码和测验分数。所以只是数字。
  • ".. 打印到屏幕上以便我可以将其扫描成一个数组"——这是什么意思?您已经将它打印到屏幕上,但这与“扫描到数组”无关。如果你的目标数组是quizarray,是不是有点小了?

标签: c file


【解决方案1】:

好的,我想我知道您想要发生什么,将 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多