当一行只包含制表符时,处理制表符描绘的文本文件

dealing with tab delineated text files when a line contains only tabs

本文关键字:制表符 处理 文件 文本 一行 包含      更新时间:2023-10-16

我正在处理一个标签划定的文本文件。我使用getline获取每一行,然后根据制表符对其进行解析,并将其放入数组中以供以后操作。偶尔,由于输入到文本文件中的数据,我要么有一个空行,要么更常见的是只有ascii制表符的行。虽然我可以回去手动修复文件,

我已经承担了这个任务,试图让我的程序处理数据。使用substr.empty()我可以处理空行并成功地忽略这些行,这就是我想要做的。行中的制表符使行不为空,这是我得到的,并导致substr。空以通过错误。使用字符串的子串。我可以处理制表符,但不能忽略有制表符的行。相反,我只是通过一个错误并将一个错误打印到输出文件,让met知道我有一个错误。

我似乎无法让这两种功能共存。我肯定我错过了一些基本的东西。一个多月来,我一直试图弄清楚这个问题,但无济于事(我不是每天都编程)。所以我正在寻找为什么我不能把。begin作为一个或布尔值与if语句空函数。为什么我不能让。begin忽略行

下面是我的代码:

ofstream file_;
ifstream file2_("forecasttest.txt");
if (file2_.is_open())
while (file2_.good()) {
    string substr;  
    getline(file2_, substr);
    string::iterator substr2 = substr.begin(); 
    //if (*substr2 == 't') {
        //  file_.open("chaz_file.txt");  
        //  if (file_.is_open())   
        //  file_ << "you have bad data - a line that starts with a tab" << endl;
        //  file_.close();
        //  return 0;
    //}
    Input_Rows++;
    if (substr.empty()) { //|| (*substr2 == 't')
        Input_Rows--;
    }
    else {
        istringstream iss(substr);
        cout << substr << endl;
        string token;
        while (getline(iss, token, 't')){   
            vec_Forecast_Data_.push_back(token);
        }
    }
}

您的代码似乎"想要"(而不是"说")做这样的事情:

如果该行为空或只有制表符,则记录一个错误,跳过该行并继续检查输入

如果这是你想要的,空(空格/制表符)的检测可以用这样的函数:

bool checkAllSpacesLine(const std::string& s) {
  size_t p, len=s.length(); // decrementing p will underflow to 
                            // greater than len once it reaches 0
  for(p=len-1; p<len && isspace(s[p]);p--);
  return p>len; // p underflow, all chars were spaces
}

检查substr是否为空或只包含制表符:

if (substr.find_first_not_of('t') == std::string::npos)