我想为10本书添加一个标题数组,用户可以在每个可能包含多个单词的标题上添加/输入“字符串值”。我试图将"char“替换为"string”,但在运行程序时它不能正常工作!
#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;
}发布于 2020-06-17 02:53:02
您应该使用std::string和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;
  }
};std::getline()将读取文本,直到找到换行符。
operator>>将跳过空格,然后读取文本,直到找到空格(通常是一个文本单词)。
https://stackoverflow.com/questions/62415411
复制相似问题