Search code examples
c++cingetline

cin is skipping a line


Here's a segment of code that I am working on:

std::cout << "Enter title of book: ";
std::string title;
std::getline(std::cin, title);
std::cout << "Enter author's name: ";
std::string author;
std::getline(std::cin, author);
std::cout << "Enter publishing year: ";
int pub;
std::cin >> pub;
std::cout << "Enter number of copies: ";
int copies;
std::cin >> copies;

Here's the output from this section when it is running (added quotes):

"Enter title of book: Enter author's name":

How do I fix this so that I can enter in the title?


Solution

  • I think you have some input before that you don't show us. Assuming you do you can use std::cin.ignore() to ignore any newlines left from std::cin.

      std::string myInput;
      std::cin >> myInput; // this is some input you never included.
      std::cin.ignore(); // this will ignore \n that std::cin >> myInput left if you pressed enter.
    
      std::cout << "Enter title of book: ";
      std::string title;
      std::getline(std::cin, title);
      std::cout << "Enter author's name: ";
    

    Now it should work.