简体   繁体   English

c ++:stringstream to vector

[英]c++: stringstream to vector

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;
}

Why are you using a stringstream to copy from a string into a vector<unsigned char> ? 你为什么要使用一个stringstream从复制stringvector<unsigned char> You can just do: 你可以这样做:

vector<unsigned char> vec(line.begin(), line.end());

and that will do the copy directly. 那将直接进行复制。 If you need to use a stringstream , you need to use stream >> noskipws first. 如果你需要使用一个stringstream ,你需要使用stream >> 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操纵器在下一个流提取( >> )操作中明确地执行此操作,如下所示:

stream >> std::noskipws >> var;

I'm inclined to suggest just using the container that you actually want but you could also use the manipulator noskipws 我倾向于建议只使用你真正想要的容器,但你也可以使用操纵器noskipws

See this for more info on stringstream and other methods you could use besides the extraction operator 有关stringstream和除抽取运算符之外可以使用的其他方法的更多信息,请参阅此内容

Edit: 编辑:

Also consider std::copy or std::basic_string<unsigned char> for simplicity. 为简单起见,还要考虑std::copystd::basic_string<unsigned char>

You want the noskipws manipulator. 你想要noskipws操纵器。 Say stream >> std::noskipws; stream >> std::noskipws; before pulling stuff out of it. 在拉出它之前。

[EDITED to add the std:: prefix, which I stupidly omitted. [编辑添加std::前缀,我愚蠢地省略了。 Your code doesn't need it because it has using namespace std; 您的代码不需要它,因为它using namespace std; at the top, but others may choose not to do that.] 在顶部,但其他人可能选择不这样做。]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM