0

I want to add an array of titles for 10 books, that the user can add/input on a "string value" on each title that may contain more than one word. I tried to replace the "char" with "string" but it doesn't work correctly when running the program!

#include <iostream>
using namespace std;
class Book {
  int year;
  char Title[10];  // the problem with in here
  int bookno;
  int copyno;
  int price;

 public:
  void Creatdata()  // Statement 1 : Defining Creatdata()
  {
    cout << "\n\tEnter Book published year : ";
    cin >> year;

    cout << "\n\tEnter Book title : ";
    cin >> Title;

    cout << "\n\tEnter Book number: ";
    cin >> bookno;
    cout << "\n\tEnter Copy number: ";
    cin >> copyno;

    cout << "\n\tEnter Employee Salary : ";
    cin >> price;
  }

  void DisplayData()  // Statement 2 : Defining DisplayData()
  {
    cout << "\n" << year << "\t" << Title << "\t" << bookno << "\t" << copyno
         << "\t" << price;
  }
};

int main() {
  int i;

  Book B[10];  // Statement 3 : Creating Array of 10 books

  for (i = 0; i <= 10; i++) {
    cout << "\nEnter details of " << i + 1 << " Book";
    B[i].Creatdata();
  }

  cout << "\nDetails of Book";
  for (i = 0; i <= 10; i++)
    B[i].DisplayData();
  return 0;
}
David G
  • 94,763
  • 41
  • 167
  • 253
  • 1
    What is wrong when you declare it as string? Also what output do you expect? – NixoN Jun 16 '20 at 18:41
  • Q: What do you mean "it doesn't work correctly when running the program!"??? Please clarify. Q: Please show us your code for "array of string". Q: You realize your current code `char Title[10]` means "a title for ONE book, maximum nine letters", don't you? – paulsm4 Jun 16 '20 at 18:45
  • Does this answer your question? [std::cin input with spaces?](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) – paulsm4 Jun 16 '20 at 18:47

1 Answers1

0

You should use std::string and std::getline:

class Book {
  int year;
  std::string title;
  int bookno;
  int copyno;
  int price;

 public:
  void Creatdata()  // Statement 1 : Defining Creatdata()
  {
    cout << "\n\tEnter Book published year : ";
    cin >> year;

    cout << "\n\tEnter Book title : ";
    std::getline(std::cin, title);

    cout << "\n\tEnter Book number: ";
    cin >> bookno;
    cout << "\n\tEnter Copy number: ";
    cin >> copyno;

    cout << "\n\tEnter Employee Salary : ";
    cin >> price;
  }
};

The std::getline() will read text until a newline is found.
The operator>> will skip spaces, then read text until white space is found (usually one text word).

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154