2013-02-10 27 views
3

我有一個整數列表,每行一個數字,並且希望將這些數字中的每一個都存儲在整數數組中,以便稍後在程序中使用。讀取txt文件中的數字列表並將其存儲到數組中C

例如在Java中,你會做這樣的事情:

FileReader file = new FileReader("Integers.txt"); 
int[] integers = new int [100]; 
int i=0; 
while(input.hasNext()) 
{ 
    integers[i] = input.nextInt(); 
    i++; 
} 
input.close(); 

怎麼會在C做?

+0

一如既往,通過張貼您在C中完成的工作來展示一些工作,解釋您是否被卡住了。 'open'和'scanf'是你的朋友... – 2013-02-10 20:57:45

+0

是的,我想知道如何在C中做到這一點。我把一個例子在Java中。 – TrialName 2013-02-10 20:57:53

+0

@LihO如果你仔細閱讀OP,這是他在java中試圖做的一個例子。 – 2013-02-10 20:58:31

回答

6

給這一去。如果您閱讀每個函數(fopen(),scanf(),fclose())的手冊頁以及如何分配C語言中的數組,您會更好。您還應該爲此添加錯誤檢查。例如,如果Integers.txt不存在或者您沒有權限讀取它,會發生什麼情況?如果文本文件包含超過100個數字,怎麼辦?

FILE *file = fopen("Integers.txt", "r"); 
    int integers[100]; 

    int i=0; 
    int num; 
    while(fscanf(file, "%d", &num) > 0) { 
     integers[i] = num; 
     i++; 
    } 
    fclose(file); 
+0

看起來不錯,但讓OP先顯示一些努力... – 2013-02-10 21:06:26

+0

雖然我寧願用'while(fscanf(file,「%d」,#num == 1))'。 – LihO 2013-02-10 21:07:32

+0

@Fredrik OP知​​道Java。 C的一個巨大障礙就是知道要調用哪些函數。希望OP會閱讀這些功能的手冊頁並瞭解它們的工作原理。 – shanet 2013-02-10 21:08:31

1
#include <stdio.h> 

int main (int argc, char *argv[]) { 
    FILE *fp; 
    int integers[100]; 
    int value; 
    int i = -1; /* EDIT have i start at -1 :) */ 

    if ((fp = fopen ("Integers.txt", "r")) == NULL) 
    return 1; 

    while (!feof (fp) && fscanf (fp, "%d", &value) && i++ < 100) 
    integers[i] = value; 

    fclose (fp); 

    return 0; 
} 
相關問題