0

So if you want to use operator>> and getline with std::cin, then you have to erase the contents of the input buffer if you want to use a getline after an operator>>. But why operator>> leaves the endline character in the input buffer?

#include <iostream>
#include <string>
#include <limits>

int main() {
    std::cout << "Please enter your username:\n";
    std::string username;
    std::cin >> username;

    //delete the value of input buffer
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cout << "Please enter your name:\n";
    std::string fullname;
    getline(std::cin, fullname);
}
christo161
  • 21
  • 2
  • When reading in a `std::string`, `operator>>` first skips whitespace, then reads in the string and stops when it hits whitespace. A newline counts as whitespace. – Eljay Dec 14 '20 at 19:35
  • 1
    @Eljay — and, to be perfectly clear, your comment describes the behavior of **all** formatted extractors, not just the one that reads into `std;;string`. They’re all consistent. – Pete Becker Dec 14 '20 at 22:10

0 Answers0