如何将文件中的明文解析成2d矩阵/数组?

时间:2012-01-05 00:10:54

标签: c file

我编写的以下代码应该转换从文件中获取的行,如下所示:

(3670, 1882) (1574, 7255) (4814, 8566) (1609, 3153) (9725, 13468) (8297, 3006) (9091, 6989) (8521, 10432) (14669, 12201) (4203, 9729) (469, 2444) (10107, 8318) (1848, 13650) (5423, 847) (11755, 8827) (4451, 4495) (11645, 1670) (10937, 5692) (14533, 13696) (7291, 12158) (1891, 2405) (1776, 4971) (2486, 2499) (13389, 236) (8533, 7531) (10618, 10288) (9119, 11226) (9429, 6622) (12380, 9516) (1698, 5828) (8369, 5101) (11341, 13530) (11955, 2335) (6249, 14435) (9373, 6921) (2977, 2294) (57, 14558) (280, 12847) (13846, 11748) (428, 9004)

进入有效的2d矩阵。

  

{{3670,1882},{1547,7255} ...}

我是一个很好的“pythoner”,我能够在一行中做到这一点。我想尝试在c中解决同样的问题(注意我今天开始乱用c);我的尝试如下(结果非常随机/错误):

FILE *fp;
fp=fopen(argv[1], "rt");

if ( fp != NULL )
{
    char line [1000]; //this is ugly, isn't this?

    while ( fgets ( line, sizeof line, fp ) != NULL ) // read a line 
    {
        line[(strlen(line)-1)] = '\0';
        //line[(strlen(line)-2)] = '\0';
        char* p;
        p = strtok(line, ",)( ");

        int elements[100][2]; //even uglier than before?
        int binpos=0;
        int pos=0;
        while (p != NULL)
        {
            if (p!=NULL){
                if (binpos==0){
                    elements[pos][binpos]=atoi(p);
                    binpos=1;
                }else{
                    p[(strlen(p)-1)] = '\0'; //remove the comma
                    elements[pos][binpos]=atoi(p);
                    pos++;
                    binpos=0;
                }
            }
            p = strtok(NULL, ",)( ");
        }
        int it;
        for (it=0; it<pos; it++){
            printf("(%d, %d)\n",elements[it][0],elements[it][1]);
        }
        return 0;
    }
}

有人可以告诉我如何纠正我的烂摊子吗? :)

1 个答案:

答案 0 :(得分:1)

如果行与您正在解析的内容相关,则应该只使用fgets来读取行。在你的情况下,看起来行结尾是无关紧要的,所以你最好只使用scanf:

printf("{");
const char *sep = "";
int a, b;
while (fscanf(fp, "(%d,%d)", &a, &b) == 2) {
    printf("%s{%d, %d}", sep, a, b);
    sep = ", "; }
printf("}");