[英]conversion to string with std::stringstream fails on white spaces
I am trying to convert any string or character or number to std::string
with std::stringstream
. 我想任何字符串或字符或数字转换
std::string
用std::stringstream
。 This is what I am doing: 这就是我在做什么:
template<typename T>
std::string toString(T a){
std::string s;
std::stringstream ss;
ss <<a;
ss >>s;
return s;
}
int main(int argc, char* argv[]) {
char s[100]="I am a string with spaces";
std::cout<<toString(s);
return 0;
}
But it fails on the first white space. 但是它在第一个空白处失败。
Output: 输出:
I
Expected Ouput: 预期的输出:
I am a string with spaces
How can I do this. 我怎样才能做到这一点。
Note: s
can contain newline character too. 注意:
s
也可以包含换行符。
You can directly access the stringified content of a stream with the std::ostringstream::str()
member function. 您可以使用
std::ostringstream::str()
成员函数直接访问流的字符串化内容。
template <typename T>
std::string toString(const T& a)
{
std::ostringstream ss;
// ↑
ss << a;
return ss.str();
// ~~~~~~~^
}
operator<<
has no problem inserting s
into the stringstream. operator<<
将s
插入字符串流没有问题。 It's no different than if you did std::cout << s
. 这与您执行
std::cout << s
没什么不同。 What you're doing wrong is extracting from the stream into s
. 您做错了什么是从流中提取到
s
。 This will only read up to a whitespace character (which includes both spaces and newlines.) To get the contents of the stream, do: 这只会读取最多一个空格字符(包括空格和换行符。)要获取流的内容,请执行以下操作:
return ss.str();
This however is just a convoluted way of doing: 但是,这只是一种复杂的操作方式:
std::string str = s;
Just reduce your entire program by 10 lines: 只需将整个程序减少10行即可:
#include <iostream>
int main(int argc, char* argv[]) {
char s[100]="I am a string with spaces";
std::cout<<std::string(s);
return 0;
}
If you really need to use stringstream, then there is one of possible solutions: (I do not pretend to have a good code) 如果您确实需要使用stringstream,那么有一种可能的解决方案:(我不假装有好的代码)
template<typename T>
std::string toString(T a) {
std::stringstream ss;
ss << a;
const char* s = ss.str().c_str();
ss.read((char *)s, ss.str().length());
return s;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.