从 C C++ 中的文件读取矩阵
只是想知道,对于存储在文件中的矩阵,即文件中的每一行都是矩阵的一行,其中元素由空格分隔,我如何预先确定矩阵的大小,然后创建一个相同大小的数组并将其读入C和C++中的数组中?如果您有一些代码示例,我们将不胜感激!
谢谢和问候!
Just wonder, for a matrix stored in a file as what it is, i.e. each line in the file being a row of the matrix where elements are separated by space(s), how can I predetermine the size of the matrix, then create an array of the same size and read it into the array in C and C++? If you have some code example, that would be appreciated!
Thanks and regards!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的东西。您需要包含向量、流和字符串。
无需提前找出向量的大小。
Something like this. You need to include vector, sstream and string.
There is no need to find out the size of the vector in advance.
在 C 中,您可以使用 fgets 一次读取一行,使用 strtok 或类似的工具来处理行,使用 atof 或 sscanf 来读取数字。可以处理第一行以确定矩阵宽度并分配内存,然后重新处理以插入第一行。如果高度可能不同,那么您要么需要动态分配内存,要么读取整个文件计数行然后重新处理它。
In C you might use fgets to read one line at a time, and strtok or similar to process the lines and atof or sscanf to read the numbers. The first line can be processed to determine the matrix width and allocate memory, then re-processed to insert the first row. If the height may be different then you would either need to dynamically allocate the memory, or read the whole file counting lines then reprocess it.
读取第一行,计算字段数,然后使用
fseek()
返回到文件的开头。Read the first row, count the fields and then use
fseek()
to go back to the start of the file.