类似于 istream::getline() 的东西,但带有替代的 delim 字符

Something like istream::getline() but with alternative delim characters?

本文关键字:字符 delim getline istream 类似于      更新时间:2023-10-16

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

我知道写一个循环很简单,但我觉得我可能错过了一些东西。是我吗?

我用的:

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

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

尽管您可以查看Boost iostreams库以查看它具有该功能。

有 std::getline。对于更复杂的场景,可以尝试使用提升拆分或regex_iterator拆分istream_iterator或istreambuf_iterator(下面是使用流迭代器的示例)。

这是一个有效的实现:

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;

Coliru上实时查看其用法

一个更通用的版本将是这个