加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何强制std :: stringstream operator >>读取整个字

发布时间:2020-12-16 04:52:24 所属栏目:百科 来源:网络整理
导读:如何强制std :: stringstream运算符读取整个字符串而不是停留在第一个空格? 我有一个模板类,它存储从文本文件中读取的值: template typename Tclass ValueContainer{protected: T m_value;public: /* ... */ virtual void fromString(std::string str) { s
如何强制std :: stringstream运算符>>读取整个字符串而不是停留在第一个空格?

我有一个模板类,它存储从文本文件中读取的值:

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.字符串只是模板的一个实例,它也必须支持其他类型.这就是为什么我想强制运算符>>模仿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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读