c/c++语言开发共享如何将文件中的明文解析成2d矩阵/数组?

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

(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} …}

我是一个很好的“python”,我能够在一条线上做到这一点。 我想尝试在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)] = ''; //line[(strlen(line)-2)] = ''; 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)] = ''; //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; } } 

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

    如果行与您正在解析的内容相关,则应该只使用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("}"); 

      以上就是c/c++开发分享如何将文件中的明文解析成2d矩阵/数组?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522058.html

      (0)
      上一篇 2020年12月9日
      下一篇 2020年12月9日

      精彩推荐