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

前端之家收集整理的这篇文章主要介绍了c – 如何强制std :: stringstream operator >>读取整个字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何强制std :: stringstream运算符>>读取整个字符串而不是停留在第一个空格?

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

  1. template <typename T>
  2. class ValueContainer
  3. {
  4. protected:
  5. T m_value;
  6.  
  7. public:
  8. /* ... */
  9. virtual void fromString(std::string & str)
  10. {
  11. std::stringstream ss;
  12. ss << str;
  13. ss >> m_value;
  14. }
  15. /* ... */
  16. };

我已经尝试设置/取消设置流标志,但它没有帮助.

澄清

该类是一个容器模板,可以自动转换为/类型T.字符串只是模板的一个实例,它也必须支持其他类型.这就是为什么我想强制运算符>>模仿std :: getline的行为.

解决方法

作为运算符>>当T = string时,我们不能满足我们的要求,我们可以为[T = string]情况编写一个特定的函数.这可能不是正确的解决方案.但是,正如一项工作所提到的那样.

如果它不符合您的要求,请纠正我.

我写了一个示例代码如下:

  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. template <class T>
  8. class Data
  9. {
  10. T m_value;
  11. public:
  12. void set(const T& val);
  13. T& get();
  14. };
  15.  
  16. template <class T>
  17. void Data<T>::set(const T& val)
  18. {
  19. stringstream ss;
  20. ss << val;
  21. ss >> m_value;
  22. }
  23.  
  24. void Data<string>::set(const string& val)
  25. {
  26. m_value = val;
  27. }
  28.  
  29. template <class T>
  30. T& Data<T>::get()
  31. {
  32. return m_value;
  33. }
  34.  
  35. int main()
  36. {
  37. Data<int> d;
  38. d.set(10);
  39. cout << d.get() << endl;
  40.  
  41. Data<float> f;
  42. f.set(10.33);
  43. cout << f.get() << endl;
  44.  
  45. Data<string> s;
  46. s.set(string("This is problem"));
  47. cout << s.get() << endl;
  48. }

猜你在找的C&C++相关文章