How to force std::stringstream operator >> to read an entire string instead of stopping at the first whitespace?
I've got a template class that stores a value read from a text file:
template <typename T>
class ValueContainer
{
protected:
T m_value;
public:
/* ... */
virtual void fromString(std::string & str)
{
std::stringstream ss;
ss << str;
ss >> m_value;
}
/* ... */
};
I've tried setting/unsetting stream flags but it didn't help.
Clarification
The class is a container template with automatic conversion to/from type T. Strings are only one instance of the template, it must also support other types as well. That is why I want to force operator >> to mimic the behavior of std::getline.
Here is a solution :
(Thanks to the original poster in C++ newsgroup)
Where do you want it to stop? If you want to read a whole line you probably need getline function, if you need an entire string stored in the streamstring object your choise is ostringstream::str method.
If you can use Boost then use boost::lexical_cast.
I'm assuming you're instantiating that template with
T = std::string
. In that case you could use getline:However, this assumes you won't accept nul-characters as valid parts of the string.
Otherwise you can write your own extractor for `T'.
There isn't a way with operator>> that I'm aware of excepted writing your own facet (operator>> stop at first character for which isspace(c, getloc()) is true). But there is a getline function in <string> which has the behaviour you want.
As operator >> is not satisfying our requirement when T=string, we can write a specific function for [T=string] case. This may not be the correct solution. But, as a work around have mentioned.
Please correct me if it won't satisfy your requirement.
I have written a sample code as below: