![](/img/trans.png)
[英]How to save looped output in C++ to a .txt file with columns and rows
[英]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.