检查 std::stringstream 是否包含字符 - 缓冲直到 \n
Check if std::stringstream contains a character - buffering until \n
因为我无法在 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 日志库。
检查流中是否包含换行符的方法是使用std::string::find_first_of
on the underlying string of the stringstream. If the stream contains a newline then we can use 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());
}
}
因为我无法在 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 日志库。
检查流中是否包含换行符的方法是使用std::string::find_first_of
on the underlying string of the stringstream. If the stream contains a newline then we can use 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());
}
}