检查 std::stringstream 是否包含一个字符 - 缓冲直到 \n [英] Check if std::stringstream contains a character - buffering until \n

查看:45
本文介绍了检查 std::stringstream 是否包含一个字符 - 缓冲直到 \n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我无法找到如何在 android 调试输出中输出原始数据(例如,没有 \n 自动插入),我决定子类化我们的日志库并将输入缓冲到 \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();
    }
}

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

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.

推荐答案

您可以检查流中是否包含换行符的方法是使用 std::string::find_first_of 在字符串流的底层字符串上.如果流包含换行符,那么我们可以使用 std::getline提取换行符之前的缓冲区部分并输出到日志中.

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

这篇关于检查 std::stringstream 是否包含一个字符 - 缓冲直到 \n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆