如何将文件中的纯文本解析为二维矩阵/数组? [英] how to parse plaintext from file into a 2d matrix/array?

查看:47
本文介绍了如何将文件中的纯文本解析为二维矩阵/数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

the following code that I wrote is supposed to transform a line taken from a file like the following:

(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)

转换为有效的二维矩阵.

into a valid 2d matrix.

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

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

我是一个很好的"pythoner",我能够一口气做到这一点.我想尝试解决c中的相同问题(请注意,今天我开始弄乱c了);我的尝试如下(结果很随机/错误):

I'm a good "pythoner" and I'd be able to do that in one line. I wanted to try to solve the same problem in c (note that I started to mess around with c today); my attempt is the following (and the result is quite random/wrong):

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;
    }
}

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

Can someone please tell me how to correct my mess? :)

推荐答案

仅当行与要解析的内容相关时,才应使用fgets读取行.就您而言,行尾似乎无关紧要,因此最好使用scanf:

You should only be using fgets to read lines if lines are relevant to what you are parsing. In your case it looks like line endings are irrelevant, so you're better off just using 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("}");

这篇关于如何将文件中的纯文本解析为二维矩阵/数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆