1

所以可以说我必须阅读文本

鲍勃 5 5 5

山姆 4 4 4

或者

2 2 2 乔

1 1 1 拉里

对数字使用单独的二维数组,对名称使用其他数组。我该怎么做呢?

我考虑过至少在第一种情况下使用

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 之类的东西的地方,你如何检查新行?我非常失去理解这些材料的任何帮助。

4

1 回答 1

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;
}
于 2013-05-16T08:43:02.653 回答