c++ - 读取包含矩阵 C++ 的文本文件

标签 c++ matrix text-files

我需要在 C++ 上编写一个简单的程序,它可以从文本文件中获取两个矩阵,还可以获取每个矩阵的行数和列数,如下所示:

这是文本文件包含的 ex

3 5
1 -2 3 4 5
1 2 -3 4 5
-1 2 3 4 5
5 4
-1 2 3 4
1 -2 3 4
1 2 -3 4
1 2 3 -4
-1 -2 -3 -4

每个矩阵的第一行包含它的行数和列数

这是我尝试做的程序

#include <cstdio>
#include <cstring>
#include <fstream>
#define Height 3
#define Width  5
// I assume that each input line in the file can contain at most width * 3 characters.
// Three extra characters for NL, CR, 0.
// Change this if you expect the file to contain longer lines.
#define BUFFER_WIDTH (Width * 3 + 3)
unsigned char Map[Height][Width];
char line[BUFFER_WIDTH];
// Remove CR, NL at the end of the line.
void clean_line(char *line)
{
 int len = strlen(line);
  while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r'))
{
 line[len - 1] = '\0';
 len--;
  }
}
int main ()
{
FILE *fp = fopen("input1.txt","r");
int row = 0;
while (!feof(fp) && row < Height)
  {
  fgets(line, BUFFER_WIDTH, fp);
  clean_line(line);
  int len = strlen(line);
  int rowLen = len > Width ? Width : len;
for (int col = 0; col < rowLen; col++)
{
  Map[row][col] = line[col];
  printf("%d  ",Map[row][col]);
 }
printf("\n");
row++;
 }
fclose(fp);
 return 0;
}

最佳答案

您需要对整个文件进行解析,然后按分隔符(在本例中为换行符和空格)将其拆分。这个过程称为标记化。许多库(如 boost 或 poco)都支持此类操作。

class StringTokenizer

boost::split

关于c++ - 读取包含矩阵 C++ 的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10071978/

相关文章:

c++ - 如何将 random_shuffle 与 CString 一起使用?

c++ - 用 C++ 将不同的结构写入文件?

c++ - 应用变换时,OpenGL 是否会更改内存中的顶点?

c++ - wntdll.pdb 未加载 - 看不到异常

c++ - C++ 程序员的 C 陷阱和错误

python - 在 2D numpy 数组的子矩阵上高效运行

c++ - 将矩阵调整为 double 组

python - 删除文本文件中的行

python - 从 Python 中的资源加载 txt 文件

bash - 合并文本文件列表(太长),在之间添加换行符分隔符