代码之家  ›  专栏  ›  技术社区  ›  1800 INFORMATION

帮助改进此ini分析代码

  •  1
  • 1800 INFORMATION  · 技术社区  · 17 年前

    这是我想出的简单方法 this question . 我对它并不完全满意,我认为它是一个帮助改进我对STL和基于流的编程的使用的机会。

    std::wifstream file(L"\\Windows\\myini.ini");
    if (file)
    {
      bool section=false;
      while (!file.eof())
      {
        std::wstring line;
        std::getline(file, line);
        if (line.empty()) continue;
    
        switch (line[0])
        {
          // new header
          case L'[':
          {
            std::wstring header;
            size_t pos=line.find(L']');
            if (pos!=std::wstring::npos)
            {
              header=line.substr(1, pos);
              if (header==L"Section")
                section=true;
              else
                section=false;
            }
          }
      break;
          // comments
          case ';':
          case ' ':
          case '#':
          break;
          // var=value
          default:
          {
            if (!section) continue;
    
    // what if the name = value does not have white space?
    // what if the value is enclosed in quotes?
            std::wstring name, dummy, value;
            lineStm >> name >> dummy;
            ws(lineStm);
            WCHAR _value[256];
            lineStm.getline(_value, ELEMENTS(_value));
            value=_value;
          }
        }
      }
    }
    

    你会怎么改进这个?请不要推荐其他库-我只想用一个简单的方法从一个ini文件中解析出一些配置字符串。

    3 回复  |  直到 17 年前
        1
  •  3
  •   Dprado    17 年前

    //如果name=value没有空格怎么办?
    //如果值用引号括起来怎么办?

    我将使用boost::regex来匹配每种不同类型的元素,比如:

    boost::smatch matches;
    boost::regex name_value("(\S+)\s*=\s*(\S+)");
    if(boost::regex_match(line, matches, name_value))
    {
        name = matches[1];
        value = matches[2];
    }
    

    正则表达式可能需要一些调整。

    我还将用std::getline替换de stream.getline,去掉静态char数组。

        2
  •  1
  •   Airsource Ltd    17 年前

    这是:

    for (size_t i=1; i<line.length(); i++)
            {
              if (line[i]!=L']')
                header.push_back(line[i]);
              else
                break;
            }
    

    应该通过调用wstrchr、wcshr、wstrchr或其他什么来简化,具体取决于您所处的平台。

        3
  •  1
  •   Adam Mitz    17 年前

    //如何一次将一行转换成字符串?

    使用(非成员) getline 来自标准字符串头的函数。