这是我为提出的简单方法这个问题。我对它并不完全满意,我认为这是一个帮助改进我对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文件中的一些配置字符串。

有帮助吗?

解决方案

  

//如果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数组。

其他提示

此:

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

应该通过调用wstrchr,wcschr,WSTRCHR或其他东西来简化,具体取决于你所使用的平台。

  

//如何一次性将一行输入一个字符串?

使用标准字符串标题中的(非成员) getline 功能。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top