我需要在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/