Check if std::stringstream contains a character - buffering until \n

不羁的心 提交于 2020-01-06 21:58:54

问题


Because I was unable to find how to output raw data in android debug output (eg. without \n automatically inserted), I decided to subclass our logging library and buffer the input until \n appears.

Our logging library accepts huge number of data formats, so I decided to create a template method:

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();
    }
}

As you can see, I don't know how to check whether the \n is in the stream and remove everything before it. Which is what I need - buffer data until \n, then send the data (without \n) to android logging library.


回答1:


On way to you can check if the stream contains a newline in it is to use std::string::find_first_of on the underlying string of the stringstream. If the stream contains a newline then we can use std::getline to extract the part of the buffer before the newline and output it to the log.

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());
    }
}


来源:https://stackoverflow.com/questions/34068094/check-if-stdstringstream-contains-a-character-buffering-until-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!