如果 INI 文件中的行长度大于 n C++,则跳过读取该行

Skip reading a line in a INI file if its length greater than n in C++

本文关键字:C++ 读取 大于 文件 INI 如果      更新时间:2023-10-16

如果超过 1000 个字符,我想跳过读取 INI 文件中的一行。这是我正在使用的代码:

#define MAX_LINE 1000
char buf[MAX_LINE];
CString strTemp;
str.Empty();
for(;;)
{
    is.getline(buf,MAX_LINE);
    strTemp=buf;
    if(strTemp.IsEmpty()) break;
    str+=strTemp;
    if(str.Find("^")>-1)
    {
        str=str.Left( str.Find("^") );
        do
        {
            is.get(buf,2);
        } while(is.gcount()>0);
        is.getline(buf,2);
    }
    else if(strTemp.GetLength()!=MAX_LINE-1) break;
}
//is.getline(buf,MAX_LINE);
return is;

我面临的问题是,如果字符超过 1000 个,则似乎陷入无限循环(无法读取下一行(。如何使获取行跳过该行并读取下一行?

const std::size_t max_line = 1000;  // not a macro, macros are disgusting
std::string line;
while (std::getline(is, line))
{
  if (line.length() > max_line)
    continue;
  // else process the line ...
}

检查 getline 的返回值并在失败时中断如何?

..或者,如果is是 iStream,您可以检查 eof(( 条件来打破您。

#define MAX_LINE 1000
char buf[MAX_LINE];
CString strTemp;
str.Empty();
while(is.eof() == false)
{
    is.getline(buf,MAX_LINE);
    strTemp=buf;
    if(strTemp.IsEmpty()) break;
    str+=strTemp;
    if(str.Find("^")>-1)
    {
        str=str.Left( str.Find("^") );
        do
        {
            is.get(buf,2);
        } while((is.gcount()>0) && (is.eof() == false));
        stillReading = is.getline(buf,2);
    }
    else if(strTemp.GetLength()!=MAX_LINE-1)
    {
        break;
    }
}
return is;

对于完全不同的东西:

std::string strTemp;
str.Empty();
while(std::getline(is, strTemp)) { 
    if(strTemp.empty()) break;
    str+=strTemp.c_str(); //don't need .c_str() if str is also a std::string
    int pos = str.Find("^"); //extracted this for speed
    if(pos>-1){
        str=str.Left(pos);
        //Did not translate this part since it was buggy
    } else
        //not sure of the intent here either
        //it would stop reading if the line was less than 1000 characters.
}
return is;

这使用字符串以方便使用,并且对行没有最大限制。 它还使用动态/魔术一切的std::getline,但我没有翻译中间的位,因为它对我来说似乎很麻烦,而且我无法解释意图。

中间的部分只是一次读取两个字符,直到它到达文件的末尾,然后之后的所有内容都会做奇怪的事情,因为你没有检查返回值。 既然是完全错误的,我就没有解释。