c++:字符串流到向量
我正在尝试将字符串流中的数据存储到向量中。我可以成功地这样做,但它会忽略字符串中的空格。如何才能将空格也推入向量中?
谢谢!
代码存根:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
stringstream s;
string line = "HELLO HELLO\0";
stringstream stream(line);
unsigned char temp;
vector<unsigned char> vec;
while(stream >> temp)
vec.push_back(temp);
for (int i = 0; i < vec.size(); i++)
cout << vec[i];
cout << endl;
return 0;
}
I'm trying to store the data that is in a stringstream into a vector. I can succesfully do so but it ignores the spaces in the string. How do I make it so the spaces are also pushed into the vector?
Thanks!
Code stub:
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
stringstream s;
string line = "HELLO HELLO\0";
stringstream stream(line);
unsigned char temp;
vector<unsigned char> vec;
while(stream >> temp)
vec.push_back(temp);
for (int i = 0; i < vec.size(); i++)
cout << vec[i];
cout << endl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么使用
stringstream
从string
复制到vector
?你可以这样做:这将直接进行复制。如果需要使用
stringstream
,则需要使用stream >>首先是 noskipws。
Why are you using a
stringstream
to copy from astring
into avector<unsigned char>
? You can just do:and that will do the copy directly. If you need to use a
stringstream
, you need to usestream >> noskipws
first.默认情况下,标准流都跳过空格。如果您希望禁用跳过空白,您可以使用 noskipws 操纵器在下一个流提取 (
>>
) 操作中明确执行此操作,如下所示:By default, the standard streams all skip whitespace. If you wish to disable the skipping of white space you can explicitly do so on the next stream extraction (
>>
) operation by using the noskipws manipulator like so:我倾向于建议只使用您真正想要的容器,但您也可以使用操纵器
noskipws
请参阅 this 有关 stringstream 的更多信息以及除提取运算符之外还可以使用的其他方法
编辑:
另请考虑
std::copy
或std::为了简单起见, basic_string
。I'm inclined to suggest just using the container that you actually want but you could also use the manipulator
noskipws
See this for more info on stringstream and other methods you could use besides the extraction operator
Edit:
Also consider
std::copy
orstd::basic_string<unsigned char>
for simplicity.您需要
noskipws
操纵器。说stream >> std::noskipws;
在从中提取内容之前。[已编辑添加
std::
前缀,我愚蠢地省略了它。您的代码不需要它,因为它的顶部有using namespace std;
,但其他人可能选择不这样做。]You want the
noskipws
manipulator. Saystream >> std::noskipws;
before pulling stuff out of it.[EDITED to add the
std::
prefix, which I stupidly omitted. Your code doesn't need it because it hasusing namespace std;
at the top, but others may choose not to do that.]