2013-05-16 14 views
1

所以可以說我有文本我對fscanf和2D數組有點困難。

閱讀鮑勃5 5 5

山姆4 4 4

2 2 2喬

111拉里

使用單獨的二維數組作爲數字和其他名稱。我該怎麼去做呢?

我想過使用至少在第一種情況下

char reading; 
int test[MAX][LEN];//where max is some #define, does not matter 
while (i<MAX && reading = fgetc(foo) !=EOF){ 
    if (j<LEN && reading != '\n){ 
     fscanf(foo, "%d", test[i][j]);//i'm really not sure. sorry :( 
     j++; 
    } 
    i++; 
} 

是否有一個地方,你會用這樣的東西在的fscanf%* C還怎麼檢查新線? 我很失去任何幫助理解材料將不勝感激。

+1

從學習['fgets()'](http://en.cppreference.com/w/c/io/fgets)如何工作開始。在你掌握了這個功能之前,我擔心這裏的任何解釋都會增加你的困惑。 – WhozCraig

+1

'fscanf'需要正在讀取的變量的地址。 –

+0

所以它需要測試[i] [j] – user2388958

回答

0
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 


#define MAX 10 
#define LEN 3 

int main(void){ 
    int test[MAX][LEN]={0}; 
    char name[MAX][64]; 
    char linebuff[128]; 
    FILE *foo; 
    int i,j,k; 

    foo=fopen("data.txt", "r"); 

    for(i=0;i<MAX && NULL!=fgets(linebuff, sizeof(linebuff), foo);++i){ 
     char *p, *endp; 
     j=0; 
     for(p=linebuff;NULL!=(p=strtok(p, " \t\n"));p=NULL){ 
      int num; 
      num=strtol(p, &endp, 10); 
      if(*endp == '\0'){ 
       if(j<LEN) 
        test[i][j++]=num; 
      } else { 
       strcpy(name[i], p);//unnecessary? 
      } 
     } 
    } 
    fclose(foo); 
    //check print 
    for(j=0;j<i;++j){ 
     printf("%s ", name[j]); 
     for(k=0;k<LEN;++k) 
      printf("%d ", test[j][k]); 
     printf("\n"); 
    } 

    return 0; 
} 
+0

對不起,但我不明白這一點。我不知道linebuffs或strtok是什麼。你能保持簡單嗎? – user2388958

+0

@ user2388958沒有庫引用? – BLUEPIXY