如何强制 std::stringstream operator >> 读取整个字符串而不是在第一个空格处停止?
我有一个模板类,用于存储从文本文件中读取的值:
template <typename T>
class ValueContainer
{
protected:
T m_value;
public:
/* ... */
virtual void fromString(std::string & str)
{
std::stringstream ss;
ss << str;
ss >> m_value;
}
/* ... */
};
我试过设置/取消设置流标志,但没有帮助。
澄清
该类是一个容器模板,可以自动转换为类型 T 或从类型 T 自动转换。字符串只是模板的一个实例,它还必须支持其他类型。这就是为什么我想强制运算符 >> 模仿 std::getline 的行为。
最佳答案
由于运算符>>在T=string时不能满足我们的要求,我们可以针对[T=string]情况编写一个特定的函数。这可能不是正确的解决方案。但是,正如变通方法所提到的。
如果不能满足您的要求,请指正。
我写了一个示例代码如下:
#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;
}
关于c++ - 如何强制 std::stringstream operator >> 读取整个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1136359/