【问题标题】:Extracting complete current line from std::istream从 std::istream 中提取完整的当前行
【发布时间】:2020-07-27 11:20:57
【问题描述】:

我正在扫描来自std::istream 的文本。扫描已经在进行中,我想提取当前正在读取的行(从头到尾)。此getCurrentLine() 函数不得修改std::istream 位置。

我写了这段代码,我觉得相当混乱。有一个更好的方法吗? (charStream_std::istream

std::string Scanner::getCurrentLine() const {
  auto pos = charStream_.tellg();

  // rewind until beginning of the line or stream
  while (charStream_.peek() != '\n' && charStream_.tellg() != 0)
    charStream_.unget();

  // consume endline character
  if (charStream_.peek() == '\n')
    charStream_.get();

  std::stringstream lineStream;
  char c;
  do {
    c = static_cast<char>(charStream_.get());
    lineStream << c;
  } while (c != '\n' && c != EOF);

  charStream_.seekg(pos);

  return lineStream.str();
}

【问题讨论】:

  • 使用 getline 代替 do-while 循环有什么问题吗?
  • 有道理。这将至少清理那部分。

标签: c++ istream istringstream istream-iterator


【解决方案1】:

使用函数std::getline(std::cin, std::string)

【讨论】:

  • getline 是从开头返回行还是从当前std::istream 位置开始返回?
猜你喜欢
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
  • 2014-01-05
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多