C++ 字符串流的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4432793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Size of stringstream
提问by user963241
Is there any direct way to calculate size of internal string in stringstream?
有什么直接的方法可以计算stringstream中内部字符串的大小吗?
Here, str()
returns a copy and then it gets the size of string.
在这里,str()
返回一个副本,然后获取字符串的大小。
std::stringstream oss("String");
oss.str().size();
采纳答案by Steve Townsend
std::stringstream oss("String");
oss.seekp(0, ios::end);
stringstream::pos_type offset = oss.tellp();
This is for the write pointer, but the result is the same for read pointer on Visual C++ v10.
这是针对写指针,但结果与 Visual C++ v10 上的读指针相同。
回答by vanneto
There is:
有:
std::stringstream oss("Foo");
oss.seekg(0, ios::end);
int size = oss.tellg();
Now, sizewill contain the size (in bytes) of the string.
现在,size将包含字符串的大小(以字节为单位)。
EDIT:
编辑:
This is also a good idea to put after the above snippet as it puts the internal pointer back to the beginning of the string.
放在上面的代码段之后也是一个好主意,因为它将内部指针放回到字符串的开头。
oss.seekg(0, ios::beg);