Reputation: 22428
I am trying to convert any string or character or number to std::string
with 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.
Upvotes: 1
Views: 2016
Reputation: 485
If you really need to use stringstream, then there is one of possible solutions: (I do not pretend to have a good code)
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;
}
Upvotes: 0
Reputation: 41
operator<<
has no problem inserting s
into the stringstream. It's no different than if you did std::cout << s
. What you're doing wrong is extracting from the stream into 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:
#include <iostream>
int main(int argc, char* argv[]) {
char s[100]="I am a string with spaces";
std::cout<<std::string(s);
return 0;
}
Upvotes: 4
Reputation: 48447
You can directly access the stringified content of a stream with the std::ostringstream::str()
member function.
template <typename T>
std::string toString(const T& a)
{
std::ostringstream ss;
// ↑
ss << a;
return ss.str();
// ~~~~~~~^
}
Upvotes: 3