Skip to main content
GameDev.net gamedev.net
🔒 Locked

to get entire buffer from stringstream

Started by seifer503 Jan 21, 2008 at 7:25 PM 4 replies 1.3k views
Original Post
seifer503
seifer503
I'm trying to create a template function to convert text to various data types:

template<typename Output, typename Input>
Output lexical_cast(Input &input) {
	std::stringstream ss;
	ss << input;
	Output output;
	ss >> output;
	return output;
}

int main () {
	using namespace std;

	string s;
	int i;
	char buf[] = "7 Hello World";

	s = lexical_cast<string>(buf);
	i = lexical_cast<int>(buf);
	
	cout << "String: " << s << " Int: " << i;
	cin.get();
	return 0;
}

However, I cannot get the entire buffer to fill the string. It only contains "7" instead of "7 Hello World". I realize I can use the str() member function of stringstream, but I want the solution to be general. Is there a way to accomplish this?
Sc4Freak
Sc4Freak
The std::stringstream::str() function should do what you want.

But in the end, why not just use boost::lexical_cast?
seifer503
seifer503
I'm trying to deserialize a vector from XML and I want to be able to use any data type. For example I want to be able to call a function like: template GetVectorFromXml(string xml, vector). Is this possible?
the_edd
the_edd
You can ether overload << and >> for std::vector<> or provide some kind of specialization for the case where Output is std::string.

Template function specialization is a little funky, so I'd go through a helper template class with a static member function. Something like:

template<typename To>struct lexical_conversion{    template<typename From>    static To convert(const From &f) { /* as before */ }};template<>struct lexical_conversion<std::string>{    template<typename From>    static std::string convert(const From &f) { /* use std::getline() */ }};template<typename To, typename From>To my_lexical_cast(const From &from){    return lexical_conversion<To>::convert(from);}
seifer503
seifer503
That was just what I needed, thank you! Are there any other types I should create specializations for? (BTW, I can't use Boost, since the project I'm working does not have it at this point)
Zahlman
Zahlman
Quote:
Original post by seifer503
That was just what I needed, thank you! Are there any other types I should create specializations for? (BTW, I can't use Boost, since the project I'm working does not have it at this point)


Zuh?

Boost is not some monolithic thing. Just download the pieces you need and add them.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.