是否可以在不使用 C++ 中的临时字符串变量的情况下从输入流中读取一行并将其传递给字符串流?
我目前做这样的阅读(但我不喜欢临时变量line
):
string line;
getline(in, line); // in is input stream
stringstream str;
str << line;
是否可以在不使用 C++ 中的临时字符串变量的情况下从输入流中读取一行并将其传递给字符串流?
我目前做这样的阅读(但我不喜欢临时变量line
):
string line;
getline(in, line); // in is input stream
stringstream str;
str << line;
下面的问题中有详细信息(根据@Martin York),直接从流读取到字符串流。这不是直接复制,因为您希望逐行处理输入,但这种方法在效率方面很难被击败。一旦原始数据位于字符串流中,您就可以使用字符范围实例化各个行。
老实说,对于一个无论如何都不是一个真正的巨大性能问题的问题来说,这可能需要做很多工作。
就像@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;
}