获取字符串流中的最后一个字符而不复制其整个缓冲区

时间:2016-04-20 12:13:52

标签: c++ string stringstream seek

如果我使用此代码:

template <typename Streamable>
/* ... */
std::stringstream ss;
ss << function_yielding_a_Streamable();
auto last_char = ss.str().back();

然后(我相信)需要创建ss缓冲区中的字符串副本,只为我获取最后一个字符,然后它将被销毁。我可以做一些更好的事情吗?也许使用seekp()方法?

1 个答案:

答案 0 :(得分:6)

你可以这样做:

char last_char;
std::stringstream ss;
ss << function_yielding_a_Streamable();
ss.seekg(-1,ios::end);//get to the last character in the buffer
ss>>last_char;