繁体   English   中英

.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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM