c++ - 如何强制 std::stringstream operator >> 读取整个字符串?

标签 c++ stl stringstream stdstring

如何强制 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/

相关文章:

c++ - 存储指针 vector 的最佳 C++11 方法

c++ - 字符串流转换错误

c++ - 使用 stringstream 输入/输出一个 bool 值

c++ - 简单的迭代算法

c++ - 如何将 const 字符串值放入 map

c++ - const_iterator 遍历引用的指针列表

为 fstreams 实现 move 的 C++0x 库

c++ - 用一对索引 STL 映射是个好主意吗?

c++ - 在一个项目中混合使用 boost 和 STL 库的缺点?

c++ - 为什么我不能从字符串复制初始化字符串流?