【问题标题】:How to use getline to delimit by comma *and* <space> in c++?如何使用getline在c ++中用逗号*和* <space>分隔?
【发布时间】:2017-01-25 00:37:04
【问题描述】:

鸡肉,出售,60

微波炉,通缉,201。

这些是我的 txt 文件中的示例行。现在这是我的代码:

while(getline(data, word, '\n')){
    ss<<word;

    while(getline(ss, word, ',')){//prints entire file
        cout<<word<<endl;
    }
}

我的输出是:

chicken
 for sale
 60

我的文件已成功逐行解析,但我还需要删除每个逗号后的空格。在此处的逗号后添加一个空格只会给我一个错误“没有匹配的函数来调用'getline(...:

 while(getline(ss, word, ', '))

解决方案:我刚刚使用了擦除功能

 if(word[0]==' '){//eliminates space
        word.erase(0,1);
    }

【问题讨论】:

  • std::getline 只能采用一个分隔符 - 您需要使用 std::substr 之类的内容处理您进一步阅读的内容
  • std::getline 是一个简单的解析函数,它提供了指定单个分隔符的选项。当你的解析要求有点复杂时,你必须自己实现你的解析算法。您的方法是正确的:将输入分解为逗号分隔的块。现在,将每个块作为一个字符串,并删除开头,可能还有尾随空格。您应该能够在您的 C++ 书中找到如何做到这一点的示例。

标签: c++


【解决方案1】:

您可以使用std::ws 删除每个部分的任何前导空格:

while(getline(ss >> std::ws, word, ','))

【讨论】:

    【解决方案2】:

    试试这样的:

    std::string line;
    std::string tok;
    while (std::getline(data, line))
    {
        std::istringstream iss(line);
        while (std::getline(iss >> std::ws, tok, ',')) {
            tok.erase(tok.find_last_not_of(" \t\r\n") + 1);
            std::cout << tok << std::endl;
        }
    }
    

    Live demo

    然后您可以将上述逻辑包装在自定义的重载 &gt;&gt; 运算符中:

    class token : public std::string {};
    
    std::istream& operator>>(std::istream &in, token &out)
    {
        out.clear();
        if (std::getline(in >> std::ws, out, ','))
            out.erase(out.find_last_not_of(" \t\r\n") + 1);
        return in;
    }
    

    std::string line;
    token tok;
    while (std::getline(data, line))
    {
        std::istringstream iss(line);
        while (iss >> tok) {
            std::cout << tok << std::endl;
        }
    }
    

    Live demo

    【讨论】:

      【解决方案3】:

      getline 只解析单个参数。
      如果要解析多个分隔符,可以使用 boost 库。

      std::string delimiters("|,:-;");
      std::vector<std::string> parts;
      boost::split(parts, inputString, boost::is_any_of(delimiters));
      for(int i = 0; i<parts.size();i++ ) {
          std::cout <<parts[i] << " ";
      }
      

      【讨论】:

        【解决方案4】:

        解决方案:我刚刚使用了擦除功能

        if(word[0]==' '){//eliminates space
            word.erase(0,1);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-27
          • 2019-08-19
          • 2013-10-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多