Search code examples
androidc++stringstream

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


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.


Solution

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