如何使用stringstream编写? [英] How do I use write with stringstream?
问题描述
我有一个向量< char>
的数据,我想写入 std :: stringstream
。
我试过:
my_ss.write(vector.data ),vector.size());
...但似乎没有在 my_ss
,我声明如下:
std :: stringstream my_ss(std :: stringstream :: binary);
为什么写不工作(应用程序不会崩溃,编译时出现0个错误,0个警告)?
对于我该怎么做可以使用 std :: ostream_iterator
:
std :: copy(vector.begin(),vector.end(),std :: ostream_iterator< char>(my_ss));
完成示例:
#include< iterator>
#include< sstream>
#include< vector>
#include< iostream>
#include< algorithm>
int main(){
std :: vector< char>向量(60,'a');
std :: ostringstream my_ss;
std :: copy(vector.begin(),vector.end(),std :: ostream_iterator< char>(my_ss));
std :: cout<< my_ss.str()<< std :: endl;
}
您也可以使用它来构造一个字符串
直接,而不必通过 stringstream
:
std :: string str(vector.begin(),vector.end()); // skip all of the copy and stringstream
I have a vector<char>
of data which I want to write into std::stringstream
.
I tried:
my_ss.write(vector.data(), vector.size());
...but it seems to put nothing into my_ss
which I declared as follows:
std::stringstream my_ss( std::stringstream::binary);
Why write is not working (app does not crash and compiles with 0 errors, 0 warnings)?
For the "how do I do it" you can use a std::ostream_iterator
:
std::copy(vector.begin(), vector.end(), std::ostream_iterator<char>(my_ss));
Complete example:
#include <iterator>
#include <sstream>
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::vector<char> vector(60, 'a');
std::ostringstream my_ss;
std::copy(vector.begin(), vector.end(), std::ostream_iterator<char>(my_ss));
std::cout << my_ss.str() << std::endl;
}
You could also just use that to construct a string
directly, without going via a stringstream
at all:
std::string str(vector.begin(), vector.end()); // skip all of the copy and stringstream
这篇关于如何使用stringstream编写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!