我是C语言编程的新手,正在寻找一种从CSV文件读取8 * 8矩阵并存储它的方法。有人可以帮忙吗?
答案 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
您应该注意以下(错误)条件:
请使用@Dave上面提到的标准库/字符串函数,并尝试我在本文中提到的算法。
答案 1 :(得分:1)
首先查看strtok
fgets
和ato(f/i)
以及fopen
。一般的想法是你读入文件,用逗号分割,然后将子串解析成你需要的形式。
答案 2 :(得分:1)