#include <iostream>
using namespace std;
class publication {
private:
string title;
float price;
public:
publication() {
this->title = "";
this->price = 0.0;
}
void getdata() {
cout << "Enter Title: ";
getline(cin, title);
cout << "Enter price: ";
cin >> this->price;
}
void putdata() {
cout << "Title: " << title << endl;
cout << "Price: " << price << endl;
}
};
class book : public publication {
private:
int pageCount;
public:
book() { this->pageCount = 0; }
void getdata() {
publication::getdata();
cout << "Enter page count: ";
cin >> pageCount;
}
void putdata() {
publication::putdata();
cout << "Page Count: " << pageCount << " pages\n";
}
};
class tape : public publication {
private:
float playingTime;
public:
tape() { this->playingTime = 0; }
void getdata() {
publication::getdata();
cout << "Enter playing time: ";
cin >> playingTime;
}
void putdata() {
publication::putdata();
cout << "Playing Time: " << playingTime << " mins\n";
}
};
int main() {
book b;
tape t;
b.getdata();
t.getdata();
b.putdata();
t.putdata();
return 0;
}
第一次getline()
可以正常工作,但是第二次调用它时,由于之前已经执行过一些cin >> value;
,因此它被跳过了。我尝试在cin.ignore()
之前添加一个getline()
,但它要么要求我在输入前按Enter,要么跳过第一个输入的第一个字符。
但是,如果我在每个cin.ignore()
块的末尾添加cin >> value;
,则可以使用。
因此,由于一个cin.ignore()
,我不得不突然在所有位置添加getline()
吗?还是getline()
是否有其他选择将空格作为输入?
在#include<iostream>
之后写入#include<string>
,然后getline将可以正常使用。