如何计算文件中的"columns"数?

How can I work out the number of "columns" in a file?

本文关键字:columns 文件 何计算 计算      更新时间:2023-10-16

我得到了以下函数;

double* insert(char *file_Name, int Rows, int Columns)
{
double* input = new double[Rows*Columns];
//insert function code
}

为了使其正常工作,我需要知道文件中的行数和列数,以便将它们传递给此函数。我已经计算出了使用的行数;

int RowCount = 0;
string rows;
while (getline(myfile, rows)) {
RowCount++;
}

然而,我在计算我的文件中有多少列时遇到了很多麻烦。

我尝试过的一种方法是尝试查找"\n"的所有实例,并在每个实例上递增一个计数器;

int ColumnCount = 0;
while (!myfile.eof()){
if(myfile.peek()=='n'){
countC++;
}
}

while循环本身从未被触发,因此"ColumnCount"保持为0

文件本身是一个庞大的数字集合,每个数字由空格分隔。

因为我很无聊…

这在边缘情况下肯定有错误(特别是与行末尾的分隔符有关;meh(,但适用于示例输入,并(通常(显示了一种可能的方法。

#include <iostream>
#include <sstream>
#include <cstring>
bool CharIsIn(const char c, const char* str, const size_t strLen)
{
for (size_t i = 0; i < strLen; i++)
if (str[i] == c)
return true;
return false;
}
// Detects the number of subsequences of "delimiters" in the line.
// 
// By default a valid delimiter is either whitespace or a tab character,
// and "empty" columns are collapsed.
size_t DetectNumColumns(
const std::string& line,
const char* delimiters = " t",
const bool collapseEmpty = true
)
{
if (line.empty())
return 0;
const size_t delimsLen = std::strlen(delimiters);
size_t result = 1;
bool lastWasDelim = true;
for (size_t pos = 0; pos < line.size(); ++pos)
{
if (CharIsIn(line[pos], delimiters, delimsLen))
{
if (!lastWasDelim || !collapseEmpty)
result++;
else if (pos == line.size()-1 && lastWasDelim && !collapseEmpty)
result++;
lastWasDelim = true;
}
else
{
lastWasDelim = false;
}
}
return result;
}
int main()
{
// Simulating your input file
std::stringstream ss;
ss << "1.5 7.6n";
ss << "2.3 4.5n";
ss << "9.9 7.5n";
bool GotColumnCount = false;
int RowCount = 0, ColumnCount = 0;
std::string line;
while (std::getline(ss, line))
{
// On the first iteration (only!) count columns.
const int columns = DetectNumColumns(line);
if (!GotColumnCount)
{
// On the first iteration, store this.
ColumnCount = columns;
GotColumnCount = true;
}
else
{
// On subsequent iterations, just ensure the column
// count is consistent.
if (columns != ColumnCount)
throw std::out_of_range("Inconsistent column count in input");
}
// Always increment the row count (this bit's easy)
RowCount++;
}
std::cout << "The input consists of " << RowCount << " rows of " << ColumnCount << " columnsn";
}

(现场演示(

突出的一点是,您需要分析至少一行文本,以了解您的分隔符出现了多少次(或分隔符序列显示了多少次,具体取决于您的确切要求(。您可能需要分析每一行文本,以验证整个文件中的列数是否一致。

我故意不修复这些错误,这不仅是因为我不会被愚弄(尽管这肯定是真的(,也是为了阻止你简单地复制/粘贴这个例子作为你的解决方案!请一定要用它来获得灵感,并想出更好的东西。

提示:如果你的分隔符总是只有一个字符(例如一个空格(,并且你不需要宽容地处理添加的前导或尾随空格之类的事情,那么DetectNumColumns会比我上面的尝试简单得多;它实际上只是在数(但一定要数你围栏的嵌板,而不是柱子!(。

您可以使用字符串流,并假设行具有不同的列。

编辑:对于您的情况,您可能不需要maxColumnCount。只需计算列数并打断即可。

int maxColumnCount = 0;
string row;
while (getline(myfile, row)) {
RowCount++;
std::istringstream iss(row);
int columnCount = 0;
for(string columnValue; iss >> columnValue; )
columnCount++;
if(columnCount > maxColumnCount)
maxColumnCount = columnCount ;
}