在 C++ 中从 istream 读取 1 行到字符串流而不使用临时变量?

发布于 2024-10-04 15:01:02 字数 214 浏览 0 评论 0原文

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

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

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

Is is possible to read one line from input stream and pass it to string stream without using temorary string variable in C++?

I currently do the reading like this (but I don't like the temporary variable line):

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薔薇婲 2024-10-11 15:01:07

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

如何将文件内容读入 istringstream?

说实话,这可能无论如何,要解决一个问题并不是一个很大的性能问题,需要做很多工作。

There is detailed info in the question below (per @Martin York) on reading direct from stream to stringstream. This is not a direct dup as you wish to handle the input line by line, but this approach will be hard to beat for efficiency. You can instantiate the individual lines using a character range once the raw data is in the stringstream.

How to read file content into istringstream?

To be honest, this may be a lot of work for a problem that's not really a huge perf concern anyway.

转身泪倾城 2024-10-11 15:01:05

就像@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;
}

Like @Steve Townsend said above, it's probably not worth the effort, however if you wanted to do this (and you knew beforehand the number of lines involved), you could do something like:

#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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文