如何强制std :: stringstream运算符>>读取整个字符串? [英] How to force std::stringstream operator >> to read an entire string?
问题描述
如何强制std :: stringstream运算符>>读取整个字符串而不是停在第一个空格?
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.
澄清
类是一个容器模板,可以自动转换到T类型。只有一个模板的实例,它也必须支持其他类型。这就是为什么我要强制操作符>>模仿std :: getline的行为。
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.
推荐答案
不满足我们的要求当T =字符串,我们可以写一个特定的函数为[T = string] case。这可能不是正确的解决方案。
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:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
template <class T>
class Data
{
T m_value;
public:
void set(const T& val);
T& get();
};
template <class T>
void Data<T>::set(const T& val)
{
stringstream ss;
ss << val;
ss >> m_value;
}
void Data<string>::set(const string& val)
{
m_value = val;
}
template <class T>
T& Data<T>::get()
{
return m_value;
}
int main()
{
Data<int> d;
d.set(10);
cout << d.get() << endl;
Data<float> f;
f.set(10.33);
cout << f.get() << endl;
Data<string> s;
s.set(string("This is problem"));
cout << s.get() << endl;
}
这篇关于如何强制std :: stringstream运算符>>读取整个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!