检查std :: stringstream是否包含一个字符 - 缓冲直到\ n

时间:2015-12-03 14:06:21

标签: android c++ stringstream

因为我无法找到如何在android调试输出中输出原始数据(例如,没有\n自动插入),我决定子类化我们的日志库并缓冲输入,直到\n出现。

我们的日志库接受大量数据格式,因此我决定创建一个模板方法:

template<typename T>
bool addToLog(std::stringstream* stream, android_LogPriority priority, T data) {
    // Add new data to sstream
    stream<<data;
    //If the stream now contains new line
    if(stream->PSEUDO_containsCharacter('\n')) {
        // remove everything before '\n' from stream and add it to string
        std::string str = stream->PSEUDO_getAllStringBefore('\n');
        // Log the line
        __android_log_print(priority, "", "%s", str.c_str());
        // Remove \n from stream
        stream->PSEUDO_removeFirstCharacter();
    }
}

正如您所看到的,我不知道如何检查\n是否在流中并删除之前的所有内容。这就是我需要的 - 缓冲数据直到\n,然后将数据(没有\n)发送到android日志库。

1 个答案:

答案 0 :(得分:2)

在你的路上可以检查流中是否包含换行符是在字符串流的基础字符串上使用std::string::find_first_of。如果流包含换行符,那么我们可以使用std::getline在换行符之前提取缓冲区的一部分并将其输出到日志中。

template<typename T>
bool addToLog(std::stringstream& stream, android_LogPriority priority, T data) {
    // Add new data to sstream
    stream << data;
    //If the stream now contains new line
    if(stream.str().find_first_of('\n', 0) != std::string::npos) {
        // remove everything before '\n' from stream and add it to string
        std::string str;
        std::getline(stream, str);  //gets output until newline and discards the newline
        // Log the line
        __android_log_print(priority, "", "%s", str.c_str());
    }
}