.txt 文件中有一个矩阵,如何从中获取行和列? C++

There is a matrix in a .txt file, how can i get the rows and columns from it? C++

我正在使用 CodeBlocks。

我的文件是这样的:

A: B w w V
B: C w A W
C: D w B X
D: E w C Y
E: F w D Z

我需要获取行数和列数,在本例中为 4x5。 (带 : 的字母不算数)

我的第一个解决方案是使用变量 counter 来计算矩阵的维数,但这不是一个好的解决方案。

什么函数可以获取.txt文件中矩阵的大小?拜托,欢迎任何意见,建议。

您需要使用getline逐行读取文件

std::vector<string> lines;
std::string line;
while(std::getlin(fileStream, line)
{
   lines.push_back(line);
}

现在你有

int rowCount = lines.size();

现在,对于每一行,您可以使用字符串流计算其中的元素数量;

std::istringstream iss (lines[i]);
std::string dummy; //used to munch the initial `a:` part of the string which  you don't need
iss >> dummy;
int numberOfColumns = 0;
char x;
while(iss >> x)
    ++numberOfColumns;