在 C++ 中从 istream 读取 1 行到字符串流而不使用临时变量?
是否可以从输入流中读取一行并将其传递到字符串流而不使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
下面的问题中有关于直接从流读取到字符串流的详细信息(根据@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.
就像@Steve Townsend 上面所说的那样,这可能不值得付出努力,但是如果你想这样做(并且你事先知道涉及的行数),你可以这样做:
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: