c++ - 不能将字符串数组声明为类成员而不是 char (C++)
问题描述
我想为 10 本书添加一组标题,用户可以在每个可能包含多个单词的标题上添加/输入“字符串值”。我试图用“string”替换“char”,但运行程序时它不能正常工作!
#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;
}
解决方案
你应该使用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;
}
};
将std::getline()
读取文本,直到找到换行符。
将operator>>
跳过空格,然后阅读文本,直到找到空格(通常是一个文本单词)。