0

Here is a link to the minimal code, and if it's gone here it is if your want to run it in cpp.sh:

#include <iostream>

int main()
{
  int num1;
  int num2;
  std::cout << "Enter num1: ";
  std::cin >> num1;
  std::cout << std::cin.get() << "\n";
  std::cout << "Enter num2: ";
  std::cin >> num2;
  std::cout << std::cin.get() << "\n";
  std::cout << "You're nums: " << num1 << ", " << num2 << "!\n";
}

I'm confused on why cin.get() returns an ASCII 'LF' (parsed to "10"), even though the cin >> num1 already read in that entire line.

Edit: This promblem arose becaues I was reading in a file using formatted extraction, and I wanted file.get() to return the next available byte after the newline used by the formatted extraction. Instead, it returned that newline. I'm confused how this does not "mess up" subsequent calls to extract, if the newline is in fact the "next available" character.

Community
  • 1
  • 1
Jacolack
  • 1,215
  • 2
  • 9
  • 23
  • 1
    Duplicate is about `std::getline`, but both `std::getline` and `std::istream::get()` are [unformatted input functions](https://en.cppreference.com/w/cpp/named_req/UnformattedInputFunction) – Yksisarvinen Nov 06 '19 at 09:57
  • 1
    If your edit is asking about "why subsequent formatted extraction works", then it's also explained in the duplicate I linked: *This is because input streams use whitespace as delimiters for input and have the `std::skipws` manipulator set on by default. Streams will discard the leading whitespace from the stream when beginning to perform formatted input.* – Yksisarvinen Nov 06 '19 at 10:06

1 Answers1

0

std::cin.get() reads the new line character stored in the input buffer after the statement std::cin >> num2; when you pressed Enter.

Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268