我正在将一些网络数据读取为stringstream作为input_buffer。
数据是由LF字符分隔的ASCII行。
input_buffer可能处于其中只有部分行的状态。
我试图调用getline ()
,但是仅当实际上是stringt流中的一个新的换行符时才调用。换句话说,它应该提取完整的行,但在缓冲区中保留部分行。
这是MVCE:
#include <string>
#include <sstream>
#include <iostream>
int
main (void)
{
std::stringstream input_buffer;
input_buffer << "test123\nOK\n";
while (input_buffer.str ().find ('\n') != std::string::npos)
{
std::string line;
std::getline (input_buffer, line, '\n');
std::cout << "input_buffer.str ().size: " << input_buffer.str ().size () << "\n";
std::cout << "line: " << line << "\n";
}
return 0;
}
它当前不会终止,这是输出的一部分:
input_buffer.str ().size: 11
line: test123
input_buffer.str ().size: 11
line: OK
input_buffer.str ().size: 11
line:
input_buffer.str ().size: 11
...
仅当字符串流包含任何换行符时,才如何读取它?
编辑:为澄清起见,这是另一个具有部分输入的代码示例:
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
void
extract_complete_lines_1 (std::stringstream &input_buffer, std::vector<std::string> &lines)
{
while (input_buffer.str ().find ('\n') != std::string::npos)
{
std::string line;
std::getline (input_buffer, line, '\n');
lines.push_back (line);
}
}
void
print_lines (const std::vector<std::string> &v)
{
for (auto l : v)
{
std::cout << l << '\n';
}
}
int
main (void)
{
std::vector<std::string> lines;
std::stringstream input_buffer {"test123\nOK\npartial line"};
extract_complete_lines_1 (input_buffer, lines);
print_lines (lines);
return 0;
}
这应该打印“test123”和“确定”,而不是“分行”。
最佳答案
如here所述,您可以覆盖缓冲区的underflow
函数,以便它将使用您可以指定的函数重新填充。
这是从here改编而成的示例:
#include <iostream>
#include <sstream>
#include <string>
class Mybuf : public std::streambuf {
std::string line{};
char ch{}; // single-byte buffer
protected:
int underflow() override {
if(line.empty()) {
std::cout << "Please enter a line of text for the stream: ";
getline(std::cin, line);
line.push_back('\n');
}
ch = line[0];
line.erase(0, 1);
setg(&ch, &ch, &ch + 1); // make one read position available
return ch;
}
public:
Mybuf(std::string line) : line{line} {};
};
class mystream : public std::istringstream {
Mybuf mybuf;
public:
mystream(std::string line) : std::istringstream{}, mybuf{line}
{
static_cast<std::istream&>(*this).rdbuf(&mybuf);
}
};
int main()
{
mystream ms{"The first line.\nThe second line.\nA partial line"};
for(std::string line{}; std::getline(ms, line); )
std::cout << "line: " << line << "\n";
}
输出:
line: The first line.
line: The second line.
Please enter a line of text for the stream: Here is more!
line: A partial lineHere is more!
Please enter a line of text for the stream: