-1

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?

Ricca
  • 311
  • 4
  • 21
  • The (currently) two answers provide solutions for what is very likely the problem, but the question is missing [the completeness requirement of MCVE](http://stackoverflow.com/help/mcve) and cannot be answered with with certainty. – user4581301 Oct 28 '15 at 23:36
  • Possible duplicate of [cin and getline skipping input](http://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input) – Mykola Oct 29 '15 at 23:46

2 Answers2

2

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.

Linus
  • 1,516
  • 17
  • 35
0

getline is newline delimited. However, reading with something like std::cin leaves the newline in the input stream. As this recommends, when switching from whitespace delimited to newline delimited input, you want to clean all newlines from the input stream by doing a cin.ignore: for example, cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');. (Of course, I am assuming you left out the cin before getline when distilling your code into an MCVE).

Pradhan
  • 16,391
  • 3
  • 44
  • 59