簡體   English   中英

C將數字從文件讀入數組

[英]C Reading numbers from file into array

嘿,即時通訊試圖從文本文件中讀取數字並將它們放入數組中,但是我在嘗試打印它們時卻得到了奇怪的數字。 文本文件如下所示:

45
77
8
...

我猜我使用的循環有問題,但是我似乎找不到答案。 謝謝你的幫助!

碼:

#define MAX_ARRAY_SIZE 20

int main(int argc, char * argv[])
{
    FILE *myFile;
    int myArray[MAX_ARRAY_SIZE];
    //char filename[32];
    //printf("enter filename\n");
    //scanf("%s", filename);

    myFile = fopen("asdf.txt", "r");
    if (!myFile) {
        printf("cant open file\n");
        return 1;
    }
    int status;
    int i = 0;
    while ((status = fscanf(myFile, "%2d", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
        ++i;
    }
    fclose(myFile);


    int a;
    for (a = 0; i < MAX_ARRAY_SIZE; ++i) {
        printf("%d ", myArray[i]);
    }
    printf("\n");
return 0;
}

嘗試這個

while ((status = fscanf(myFile, "%d\n", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
    ++i;
}

問題出在您的打印循環中:

for (a = 0; i < MAX_ARRAY_SIZE; ++i)

無法保證您正在讀取MAX_ARRAY_SIZE值。 另外,如果您使用'a'作為循環迭代器,則需要使用'a' 您的循環應為:

for (a = 0; a < i; ++a)
    printf("%d ", myArray[a]);

您也不需要格式說明符中的字段寬度, fscanf(myFile, " %d", &myArray[i]))就可以了。

是的...我還沒有看到打印循環代碼。 問題在打印循環中而不是fscan,請忽略我的回答

暫無
暫無

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

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