Touloudou
Touloudou

Reputation: 2223

Extracting complete current line from std::istream

I am scanning text coming from a std::istream. The scanning is already under way, and I would like to extract the line that is currently being read (from beginning to end). This getCurrentLine() function must not modify the std::istream position.

I wrote this piece of code, which I find rather messy. Is there a better way to do this? (charStream_ is the 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();
}

Upvotes: 0

Views: 275

Answers (1)

Niklas Klausberger
Niklas Klausberger

Reputation: 27

use the function std::getline(std::cin, std::string)

Upvotes: 0

Related Questions