2013-09-23 149 views
2

這是我第一次在這裏問一個問題,所以我會盡我所能。我在C方面並不是很棒,我只是在中級C編程。搜索和閱讀文本文件

我想寫一個程序,讀取一個文件,我工作。但是我要搜索一個單詞,然後將單詞保存到數組中。我現在要去的是

for(x=0;x<=256;x++){ 
fscanf(file,"input %s",insouts[x][0]); 
} 

在文件中有一些行說「input A0;」我希望它能將「A0」保存到insouts [x] [0]。 256只是我挑選的一個數字,因爲我不知道它可能在文本文件中有多少輸入。

我insouts聲明:

char * insouts[256][2]; 
+0

什麼問題?什麼不行? –

+0

它不會將「A0」保存到數組中,或者至少這是我在嘗試打印出來時得到的結果。我只是給出了一堆奇怪的字符 – TylerM

+0

檢查'fscanf()'的返回值。對於你的格式,它會在成功時返回1,否則返回0或-1。數據必須包含交替的「輸入」和「值」(值可以改變拼寫,但輸入不能)。它們之間必須有空格。我會在格式化字符串的開頭放一個空格來跳過前導空格('「input%s」')。如果你的數據沒有這樣格式化,你可能需要使用'fgets()'然後''sscanf()'來代替'fscanf()'。我希望'fscanf()'更容易使用,因此更容易教授;這是一個雷區滿或新手陷阱。 –

回答

0

使用fgets() & sscanf()。格式化掃描分開I/O。

#define N (256) 
char insouts[N][2+1]; // note: no * and 2nd dimension is 3 
for(size_t x = 0; x < N; x++){ 
    char buf[100]; 
    if (fgets(buf, sizeof buf, stdin) == NULL) { 
    break; // I/O error or EOF 
    } 
    int n = 0; 
    // 2 this is the max length of characters for insouts[x]. A \0 is appended. 
    // [A-Za-z0-9] this is the set of legitimate characters for insouts 
    // %n record the offset of the scanning up to that point. 
    int result = sscanf(buf, "input %2[A-Za-z0-9]; %n", insouts[x], &n); 
    if ((result != 1) || (buf[n] != '\0')) { 
     ; // format error 
    } 
} 
0

你想通過數組的第X個元素,而不是存儲在那裏的值的地址。您可以使用運營商的地址&來執行此操作。

我覺得

for(x = 0;x < 256; x++){ 
    fscanf(file,"input %s", &insouts[x][0]); 
    // you could use insouts[x], which should be equivalent to &insouts[x][0] 
} 

會做的伎倆:)

而且,你只分配,每串2個字節。請記住,字符串需要由空字符終止,所以你應該數組分配改爲

char * insouts[256][3]; 

不過,我敢肯定%s的匹配A0;並不僅僅是A0,所以你可能也需要考慮到這一點。您可以使用%c和寬度一起讀取給定數量的字符。但是,您添加要自己添加空字節。這應該工作(未測試):

char* insouts[256][3]; 
for(x = 0; x < 256; x++) { 
    fscanf(file, "input %2c;", insouts[x]); 
    insouts[x][2] = '\0'; 
} 
+0

好吧,我試過,但是當我試圖打印出來,似乎我只是隨機字母。 (「%c」,insouts [x] [1]); printf(「%c」,insouts [x] [2]); – TylerM

+0

Hm,take看看我的編輯,看看是否可行:)順便說一句,使用printf(「%s \ n」,insouts [x]);打印。 –

+0

不,仍然沒有工作。只是隨機字母仍然。在該文件中: 輸入A0; 輸入A1; 輸入A2; 輸入A3; 輸入B0; 輸入B1; 輸入B2; 輸入B3;輸出GT; ; 輸出LT; 所以,如果我跟着你,它應該打印輸入清單的權利? – TylerM

0

而不是試圖使用fscanf爲什麼你不使用「getdelim」與';'作爲分隔符。根據手冊頁

「getdelim()的工作方式類似於getline在文件結束前沒有出現在輸入中。「

所以,你可以這樣做(未經測試和未編譯的代碼)

char *line = NULL; 
size_t n, read; 
int alloc = 100; 
int lc = 0; 
char ** buff = calloc(alloc, sizeof(char *)); // since you don't know the file size have 100 buffer and realloc if you need more 
FILE *fp = fopen("FILE TO BE READ ", "r"); 
int deli = (int)';'; 
while ((read = getline(&line, &n, fp)) != -1) { 
    printf("%s", line); // This should have "input A0;" 
    // you can use either sscanf or strtok here and get A0 out 
    char *out = null ; 
    sscanf(line, "input %s;", &out); 
    if (lc > alloc) { 
     alloc = alloc + 50; 
     buff = (char **) realloc(buff, sizeof(char *) * alloc); 
    } 
    buff[lc++] = out 
} 

int i = 0 ; 
for (i = 0 ; i < lc; i++) 
    printf ("%s\n", buff[i]); 
+0

我敢肯定,作品,並感謝你需要幫助,但我並不特別瞭解其中的一些情況,我知道我們還沒有在課堂上進行分配,因爲他說我們很快就會開始。 – TylerM