像istream :: getline()之类的东西,但有替代的delim字符?

时间:2012-10-15 07:10:19

标签: c++ getline text-parsing istream

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

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

我用过的东西:

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

3 个答案:

答案 0 :(得分:3)

std::getline。 对于更复杂的方案,可以尝试使用istream_iteratoristreambuf_iteratorboost split使用流迭代器来分割regex_iteratorhere is an example

答案 1 :(得分:3)

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

虽然您可以查看Boost iostreams库以查看它,但它具有相应的功能。

答案 2 :(得分:0)

这是一个有效的实施方案:

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