【问题标题】:Read 1 line from istream to string stream without temporary variable in C++?在 C++ 中没有临时变量的情况下从 istream 读取 1 行到字符串流?
【发布时间】:2011-05-15 21:00:39
【问题描述】:

是否可以在不使用 C++ 中的临时字符串变量的情况下从输入流中读取一行并将其传递给字符串流?

我目前是这样阅读的(但我不喜欢临时变量line):

string line;
getline(in, line); // in is input stream
stringstream str;
str << line;

【问题讨论】:

    标签: c++ stream iostream stringstream istream


    【解决方案1】:

    就像@Steve Townsend 上面所说的那样,这可能不值得付出努力,但是如果您想这样做(并且您事先知道所涉及的行数),您可以执行以下操作:

    #include <iostream>
    #include <iterator>
    #include <string>
    #include <sstream>
    #include <algorithm>
    
    using namespace std;
    
    template <typename _t, int _count>
    struct ftor
    {
      ftor(istream& str) : _str(str), _c() {}
    
      _t operator() ()
      { 
        ++_c;
        if (_count > _c) return *(_str++); // need more
        return *_str; // last one
      }
    
      istream_iterator<_t> _str;
      int _c;
    };
    
    int main(void)
    {
      ostringstream sv;
      generate_n(ostream_iterator<string>(sv, "\n"), 5, ftor<string, 5>(cin));
    
      cout << sv.str();
    
      return 0;
    }
    

    【讨论】:

    • 您正在阅读文字,而不是线条。无需事先了解行数,即可轻松测试流结束。只需使用 void*operator。
    【解决方案2】:

    下面的问题(根据@Martin York)提供了有关从流直接读取到字符串流的详细信息。这不是直接复制,因为您希望逐行处理输入,但这种方法在效率方面很难被击败。一旦原始数据位于字符串流中,您就可以使用字符范围实例化各个行。

    How to read file content into istringstream?

    说实话,对于一个实际上并不是一个真正的性能问题的问题来说,这可能需要做很多工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2022-11-28
      相关资源
      最近更新 更多