【问题标题】:Count How Many Data Groups in File C++计算文件 C++ 中有多少个数据组
【发布时间】:2021-04-25 00:57:38
【问题描述】:

我有一个这样的数据文件;

  # Some Word n: 3   other word
  # Paarthunax is over age 100
  2.230  4.940  1.934  4.328
  3.340  4.470  4.023  3.546
  5.734  3.570  2.194  2.147
 

  # Some Word
  # Some other Words      123
  # Words a: 23    1.232323  : 12312321.123123    
  1.132  2.323  4.323  3.342
  1.131  1.233  5.232  4.432
  1.131  3.123  5.232  4.432

  1.131  1.123  4.232  5.442      
  1.134  3.333  2.423  4.312
  1.135  2.143  1.242  1.412    

我的数据文件包含这么多数据组; 每个数据组都有描述行(以 # 开头的行)。数据组中可能有空行,数量未知。未知数量的数据组描述行(可能是任何东西)。数据组之间的空行数未知,数据组行数未知。 数据线可能采用科学计数法 (1.230E-01)。

我不想从中读取数据,我已经在使用向量手动进行。 我只需要计算文件中有多少个数据组,但我无法为这种文件找出合理的模式。

我为此定义了三个函数;

unsigned int get_number_of_lines(const string& file_name){
unsigned int number_of_lines = 0;
string all_lines;
ifstream file(file_name);
while(getline(file, all_lines)){
    ++number_of_lines;
}
file.close();
return number_of_lines;
}
bool is_header(string line) {
    bool a = (line.find("#") != string::npos);
    return a;
}
int get_number_of_data_lists(string filename) {
int number_of_datalist;
ifstream stream(filename);
string line, subLine;
int i = 0;
while (i < get_number_of_lines(filename)){
    getline(stream, line);
    if(is_header(line)){
      ifstream sub_stream(filename);
      getline(sub_stream, subLine);
      while (is_header(subLine)){
            }
        }
    }
return number_of_datalist;
   }

我无法获得其余的 get_munber_of_data_lists() 我愿意接受任何建议。

【问题讨论】:

  • 这里有一个简单的方法来弄清楚如何做到这一点,它永远不会失败。只需拿出一张白纸。用简单的英语用简短的句子写下来,这是一个循序渐进的过程。完成后,call your rubber duck for an appointment。通常,我们不会在 Stackoverflow 上为其他人编写代码。我们总是向您的橡皮鸭提出此类问题。在您的橡皮鸭批准您提出的行动计划后,只需将您写下的内容直接翻译成 C++。任务完成!
  • 一些建议,没有必要,也不是一个好主意,打开同一个文件三次来回答这个问题。您应该能够通过打开文件一次并通过文件来找到组数。请注意,您有三种行(不是两种)标题行、数据行和空白行。解决此类问题的简单方法是将其视为最终状态机 (FSM)。对此进行一些阅读并制定一个简单的 FSM 来计算答案。编写代码很简单,你就完成了。

标签: c++ file find ifstream getline


【解决方案1】:

我会逐行阅读:

std::vector<std::vector<double>> database;
//...
std::string text_line;
while (std::getline(file, text_line))
{
    // Ignore comment and blank lines.
    if ((text_line[0] == '#') || (text_line.empty()))
    {
        continue;
    }
    // Process the data in the text line.
    bool is_data_line = true;
    while (is_data_line)
    {
        std::istringstream record_stream(text_line);
        std::vector<double> data_row;
        double number;
        while (record_stream >> number)
        {
            data_row.push_back(number);
        }
        database.push_back(data_row);
        std::getline(file, text_line);
        if ((text_line[0] == '#') || (text_line.empty()))
        {
            break;
        }
    }
}

以上代码读取一组数据。
OP 需要修改上面的代码来处理多组数据。

【讨论】:

  • 我已经在使用其他功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
  • 2019-04-30
  • 2018-07-24
  • 2012-09-29
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多