簡體   English   中英

C. 當圖形包含 2 個整數時,方法無法從文本文件中正確讀取

[英]C. Method not reading correctly from textfile when figure contains 2 integers

我有一個基本的數學程序,我將結果存儲在一個文本文件中。 每個結果都存儲在文本文件的新行中,數字在 0 到 15 之間變化。

文本文件看起來像這樣;

1
0
4
9
12
etc.

每個數字都在一個新行上(不知道為什么這里的數字在同一行上)。

程序應該找到最高的結果。 是否存在多個具有相同值的數字並不重要。

我的問題是,當數字包含兩個整數時,我的方法只取最后一個並存儲它。 例如,如果我有 15 個,則存儲 5 個。

我的方法看起來像這樣。 會很高興提供一些幫助!

void BestResult(){

    char c;
    int max=0;
    int converted=0;

    if (access("ResultScore.txt", F_OK) != -1){
        fPointerScore=fopen("ResultScore.txt", "rt");
        while((c=fgetc(fPointerScore))!=EOF){
        converted=atoi(&c);
        if (converted>max){
            max=converted;
        }
        }
        printf("\nThe best result is : %d/15 at the moment", max);

    }

    AskUserWhatToDo();

}

您將它存儲在一個字符中。 所以 char 將只存儲 '5' 而不是 '15'。 使用數據類型 string 或 char*。

您的代碼有問題,它讀取所有字符(在您的文件中一個一個)

您的代碼需要檢測行尾

ch!= '\n'

嘗試這個:

 char buffer[10]; /* as big as the biggest number */
    char ch;
    int i = 0;
    double d, dMax = 1000, dMin = -1000;

    while ((ch= getc(fp)) != EOF) {
        if (ch!= '\n')
            buffer[i++] = ch;
        else {
            buffer[i] = '\0';
            d = atof(buffer);
            if (d > dMax) dMax = d;
            if (d < dMin) dMin = d;
            i = 0;
       }
    }

就個人而言,我會以這種方式解決問題

int BestResult(FILE *infile) {
    char buf[100];
    int len=0;
    int i=0;

    while(fgets(buf,sizeof(buf),infile)!=NULL)
        len++;

    rewind(infile);

    int *numbers;
    numbers = (int *) malloc (len * sizeof(int));

    while(fgets(buf,sizeof(buf),infile)!=NULL)
        sscanf(buf,"%i",&numbers[i]);

    int maxnum=numbers[0];

    for(i=1;i<len;i++)
        if(numbers[i]>maxnum)
            maxnum=numbers[i];

    return maxnum;

}

因此,首先讀取定義您案例中元素數量的文件的大小,然后將一個整數數組分配給您找到的項目數,通過使用fgets逐行解析來填充該數組,並使用sscanf填充該數組,然后研究maxnumber。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM