[英]know the number of columns from text file, separated by space or tab
我需要知道带有浮点数的文本文件中的列数。
我这样做是为了知道行数:
inFile.open(pathV);
// checks if file opened
if(inFile.fail()) {
cout << "error loading .txt file for reading" << endl;
return;
}
// Count the number of lines
int NUMlines = 0;
while(inFile.peek() != EOF){
getline(inFile, dummyLine);
NUMlines++;
}
inFile.close();
cout << NUMlines-3 << endl; // The file has 3 lines at the beginning that I don't read
.txt的一行:
189.53 58.867 74.254 72.931 80.354
值的数量可以因文件而异,但不能在同一文件上。
每个值在“。”之后都有可变的小数位数。 (点)
这些值可以用空格或TAB分隔。
谢谢
给定您已阅读的一行,称为line
它可以工作:
std::string line("189.53 58.867 74.254 72.931 80.354");
std::istringstream iss(line);
int columns = 0;
do
{
std::string sub;
iss >> sub;
if (sub.length())
++columns;
}
while(iss);
我不喜欢先读取整行,然后重新解析,但是行得通。
有分割字符串的各种其他的方式如升压转换器的<boost/algorithm/string.hpp>
见以前的帖子在这里
您可以阅读一行,然后将其拆分并计算元素数量。
或者,您可以读取一行,然后将其作为数组进行遍历,并计算空格和\\t
字符的数量。
如果这三个假设是正确的,则可以很容易地做到这一点:
dummyLine
,以便您可以在while
循环范围之外访问它 while
循环后dummyLine
包含的内容) 如果所有这些都是正确的,那么在while
循环之后,您只需要执行以下操作:
const int numCollums = std::count( dummyLine.begin(), dummyLine.end(), '\t' ) + std::count( dummyLine.begin(), dummyLine.end(), ' ' ) + 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.