知道文本文件中的列数,以空格或制表符分隔 [英] know the number of columns from text file, separated by space or tab
问题描述
我需要知道带有浮点数的文本文件中的列数.
I need to know the number of columns from a text file with floats.
我这样做是为了知道行数:
I've made like this to know the number of lines:
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
值的数量可能因文件而异,但不能在同一文件上.
The number of values can vary from file to file but not on the same file.
每个值在."之后都有可变的小数位数. (点)
Each value have a variable number of decimal places after the "." (dot)
这些值可以用空格或TAB分隔.
The values can be separated by a space or a TAB.
谢谢
推荐答案
给出您已阅读的名为line
的行,此行有效:
Given a line you have read, called line
this works:
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);
我不喜欢这样先读取整行,然后重新解析它,但是行得通.
I don't like that this reads the whole line, and then reparses it, but it works.
还有多种其他分割字符串的方法,例如boost的<boost/algorithm/string.hpp>
参见上一篇文章此处
There are various other ways of splitting strings e.g. boost's <boost/algorithm/string.hpp>
See previous post here
这篇关于知道文本文件中的列数,以空格或制表符分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!