寻找一种从CSV文件中读取8 * 8矩阵并存储它的方法

时间:2011-12-19 16:10:51

标签: c input matrix

我是C语言编程的新手,正在寻找一种从CSV文件读取8 * 8矩阵并存储它的方法。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

我看到你提到了一个8×8矩阵。因此,当您知道维度时,您可以静态分配2d数组。否则,您可能必须解析文件一次以找到n X m,然后相应地动态分配内存(如果您动态分配内存,请不要忘记释放它!)。

您的基本算法应类似于以下内容:

initialize _matrix_
initialize _row_ and _column_ to 0

open the file 
read a line
while the currently read line is not an empty line  
    split the line using comma as a delimiter
    initialize the _column_ to zero
    for all the elements (in the output of split)
        add the element to _matrix_[_row_][_column_]
        increment the _column_ by one
    increment the _row_ by one 
    read the next line
close the file

您应该注意以下(错误)条件:

  • csv文件不存在(打开失败)
    • 如果矩阵是动态分配的,那么在退出之前将其释放!
  • csv文件为空(零行)
  • csv文件包含不是csv格式的行(解析错误)
  • 文件的内容属于哪种类型? char还是int?什么范围? (数据类型错误)
  • 如果有超过8 x 8个元素怎么办?忽略他们?

请使用@Dave上面提到的标准库/字符串函数,并尝试我在本文中提到的算法。

答案 1 :(得分:1)

首先查看strtok fgetsato(f/i)以及fopen。一般的想法是你读入文件,用逗号分割,然后将子串解析成你需要的形式。

答案 2 :(得分:1)

ABNF可以在这里找到。

使用Bison,您可以使用此语法进行解析。

这当然是一种矫枉过正,但你会学到很多很好的解析工具,将来可以派上用场。