0
struct book {
  int bookid;
  string bookname;
  float prize;
};
     

int main(){
        book b1;
        cout<<"Enter bookid"<<" "<<"Enter bookname"<<" "<<"enter prize"<<endl;
        cin>>b1.bookid;
        getline(cin,b1.bookname);
        cin>>b1.prize;
        cout<<b1.bookid<< " "<<b1.bookname<<" "<<b1.prize<<endl;
        return 0;
}

But after taking book name, it skips taking prize and direct show output.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
  • 2
    The reason is that different styles of input on the same stream (e.g. `cin >> b1bookid` `getline(cin,b1.bookname)`) handle whitespace differently, therefore give strange interactions depending on what the user enters. The *reliable* solution is to interact with the stream using one style (e.g. read everything from `cin` using `getline()` and then check/parse the input). – Peter Jan 17 '22 at 13:13
  • 1
    Does this answer your question? [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) (Depending on how you enter the input this issue will come up) – Lukas-T Jan 17 '22 at 13:17

1 Answers1

0

You need to add cin.ignore() after cin>> b1.bookid; to flush the newline character out of the buffer in between as shown below:


#include <iostream>
#include <string>
struct book {
  int bookid;
  std::string bookname;
  float prize;
};
     

int main(){
        book b1;
        std::cout<<"Enter bookid"<<" ";
        std::cin>>b1.bookid;
        
        std::cin.ignore(); //ADDED THIS 
        
        std::cout<<"Enter bookname";
        std::getline(std::cin,b1.bookname);
        
        std::cout<<"enter prize"<<std::endl;
        std::cin>>b1.prize;
        std::cout<<b1.bookid<< " "<<b1.bookname<<" "<<b1.prize<<std::endl;
        return 0;
}

The output of the above program can be seen here.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • This solution will not work, if you enter additional spaces after the number and before pressing enter. Either read all characters until newline (with the `ignore` function, see example in CPP reference: https://en.cppreference.com/w/cpp/io/basic_istream/ignore), or use the idiomatic correct approach `std::getline(std::cin >> std::ws, b1.bookname);`. Additionally. Maybe you could consider to stop your usual pattern to just drop code, and give some explanations. Maybe you can delete your answer or at least update it . . . – A M Jan 17 '22 at 13:34
  • @ArminMontigny I have mentioned at the end of my edited answer that not to mix `getline` and `cin`. For OP's original question my answer/explanation is enough. – Jason Jan 17 '22 at 13:39