【问题标题】:Something like istream::getline() but with alternative delim characters?像 istream::getline() 但带有替代分隔符的东西?
【发布时间】:2012-10-05 03:25:13
【问题描述】:

获得istream::getline(string, 256, '\n' OR ';') 效果的最干净的方法是什么?

我知道编写循环非常简单,但我觉得我可能会遗漏一些东西。我是吗?

我用了什么:

while ((is.peek() != '\n') && (is.peek() != ';'))
    stringstream.put(is.get());

【问题讨论】:

    标签: c++ getline text-parsing istream


    【解决方案1】:

    不幸的是,没有办法有多个“行尾”。你可以做的是用例如阅读该行std::getline 并将其放入 std::istringstream 并在 istringstream 的循环中使用 std::getline(带有 ';' 分隔符)。

    尽管您可以查看Boost iostreams 库来查看它是否具有相应的功能。

    【讨论】:

    • 好的,谢谢,太好了!我写了一个循环,std::stringstream.put():ed 每个字符,直到找到'\n'或';',然后使用 stringstream.str() 来获取字符串。
    【解决方案2】:

    std::getline。 对于更复杂的场景,可以尝试将istream_iteratoristreambuf_iteratorboost splitregex_iterator 分开(here is an example 使用流迭代器)。

    【讨论】:

    • std::getline 很好,因为它对std::string 有一个重载,这使得字符串 I/O 变得非常容易(至少在我看来)。
    • std::getline 在这种情况下当 OP 需要多个行尾/分隔符时无济于事。
    【解决方案3】:

    这是一个有效的实现:

    enum class cascade { yes, no };
    std::istream& getline(std::istream& stream, std::string& line, const std::string& delim, cascade c = cascade::yes){
        line.clear();
        std::string::value_type ch;
        bool stream_altered = false;
        while(stream.get(ch) && (stream_altered = true)){
            if(delim.find(ch) == std::string::npos)
                line += ch;
            else if(c == cascade::yes && line.empty())
                continue;
            else break;
        }
        if(stream.eof() && stream_altered) stream.clear(std::ios_base::eofbit);
        return stream;
    }
    

    cascade::yes 选项可折叠找到的连续分隔符。使用cascade::no,它将为每找到一个连续的第二个分隔符返回一个空字符串。

    用法:

    const std::string punctuation = ",.';:?";
    std::string words;
    while(getline(istream_object, words, punctuation))
        std::cout << word << std::endl;
    

    查看其用法Live on Coliru

    更通用的版本是this

    【讨论】:

      猜你喜欢
      • 2013-10-21
      • 2016-10-27
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      相关资源
      最近更新 更多