直接从std :: istream读入std :: string [英] Reading directly from an std::istream into an std::string

查看:865
本文介绍了直接从std :: istream读入std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有反正读取已知数量的字节,直接到std :: string,而不创建一个临时缓冲区这样做?



例如, do it by

  boost :: uint16_t len; 
is.read((char *)& len,2);
char * tmpStr = new char [len];
is.read(tmpStr,len);
std :: string str(tmpStr,len);
delete [] tmpStr;


解决方案

std :: string 有一个可以使用的 resize 函数,或者一个同样的构造函数:

  boost :: uint16_t len; 
is.read((char *)& len,2);

std :: string str(len,'\0');
is.read(& str [0],len);

这是未经测试的,我不知道字符串是否有连续存储。 p>

Is there anyway to read a known number of bytes, directly into an std::string, without creating a temporary buffer to do so?

eg currently I can do it by

boost::uint16_t len;
is.read((char*)&len, 2);
char *tmpStr = new char[len];
is.read(tmpStr, len);
std::string str(tmpStr, len);
delete[] tmpStr;

解决方案

std::string has a resize function you could use, or a constructor that'll do the same:

boost::uint16_t len;
is.read((char*)&len, 2);

std::string str(len, '\0');
is.read(&str[0], len);

This is untested, and I don't know if strings are mandated to have contiguous storage.

这篇关于直接从std :: istream读入std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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