0

I want from user a page number and and a book name, then display it by using classes and set() get() functions.However,I couldn't understand why my function sending just the integer value to the function in class and not taking the info in string.

enter code here
#include<string>
#include<iostream>
using namespace std;

class Book
{
private:
int Page;
string Name;
public:
Book(int page,string name)
{

    setPage(page);
    setName(name);
}
void setPage(int page)
{
Page=page;
}
int getPage()
{
return Page;
 }
void setName(string name)
{
Name=name;
 }
string getName()
 {
return Name;
 }
 };
int main()
{
int pages;
string nameofbook;

cout<<"Please enter the page of the book: ";
cin>>pages;

cout<<"Please enter name of the book: ";
getline(cin,nameofbook);

Book mybook(pages,nameofbook);

cout<<mybook.getName()<<"has"<<" "<<mybook.getPage()<<"pages"<<endl;

return 0;

 }
  • 1
    Did you notice it also wasn't waiting for you to input the string? If you mix `>>` and `getline` there are steps you need to take to make it work. https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction – Retired Ninja Aug 19 '20 at 06:09
  • 1
    Please, run your code in the debugger (step-wise). Btw. your assumption _and not taking the info in string._ is wrong. It's the `getline()` which just reads a `\n` left from the previous `cin>>pages;`. So, it correctly stores an empty string as name. – Scheff's Cat Aug 19 '20 at 06:10
  • 1
    The programmer's secret weapon is the debugger. It allows you to run the program at your own speed so you can see what the program does as it does it. When you catch the program doing something you didn't expect, you probably found a bug. – user4581301 Aug 19 '20 at 06:12
  • 1
    You may wish to reconsider your use of what are often considered bad practices: [`using namespace std;`](http://stackoverflow.com/q/1452721/1171191) and [`endl`](https://accu.org/index.php/journals/2619) ([another for `endl`](https://www.youtube.com/watch?v=6WeEMlmrfOI)) (those are links to explanations). – BoBTFish Aug 19 '20 at 06:13
  • OT: Proper code indentation and formatting is important. Poorly formatted code is hard to read and hard to debug. Format your code like the samples in your beginners C++ text book. – Jabberwocky Aug 19 '20 at 06:23
  • After taking the int value from the user, I added cin.ignore(); command then took string value from user and problem solved. – mel eripoza Aug 19 '20 at 11:20

0 Answers0