0

I have the following code:

`#include<iostream>
using namespace std;
struct book
{
int id;
char name[50];
int price;
};
int main()
{
book b1;
book input();
b1=input();
void display(book );
display( b1);
return 0;
}
book input()
{
book b;
cout<<"Enter the following details:";
cout<<"Book Id: ";
cin>>b.id;
cout<<"Book Name: ";
cin.getline(b.name, 50);
cout<<"Price: ";
cin>>b.price;
return (b);
}
void display(book b)
{
cout<<"Name: "<<b.name<<endl;
cout<<"ID: "<<b.id<<endl;
cout<<"Price: "<<b.price;
}

`

This program doesnot produce any error on compilation. However when run, it takes input for book id but skips the name part and again takes input for price. I couldn't figure out why is that happening.

Learn Code
  • 13
  • 2
  • What do you mean *skips* ? Does it not print `Book Name: ` at all? – pacukluka May 18 '20 at 13:24
  • There is still a newline waiting to be read after the `cin >> b.id`, so `cin.getline` reads until that newline, and you get an empty string. – Botje May 18 '20 at 13:26
  • See this question for a similar problem and solution: [test case incorrect for paranthesis checker code. For '(()' output sould be 'not balanced' but i'm getting 'balanced'](https://stackoverflow.com/questions/61792911/test-case-incorrect-for-paranthesis-checker-code-for-output-sould-be-not) – Botje May 18 '20 at 13:26
  • [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Yksisarvinen May 18 '20 at 13:30

1 Answers1

0

Quoting from the answer in this question: getline() does not work if used after some inputs

When cin.getline() reads from the input, there is a newline character left in the input stream, so it doesn't read your c-string. Use cin.ignore() beore calling getline().