为什么 struc 中的 bool 成员不接受用户输入?



我正在创建一个名为struct Car的函数,它接受两个成员值的用户输入(在int main中(。其中一个成员是bool(isElectric(,但我似乎不明白为什么程序不允许我在输入"后输入任何其他内容;真";或";false";。输出失败的原因是什么?

#include <iostream>
#include <string>
using namespace std;
struct Car {
string color;
string model;
int year;
bool isElectric;
double topSpeed;
};

int main() {

Car car1;
cout << "Enter information for Car 1." << endl;
cout << "Car Color?: ";
cin >> car1.color;
cin.ignore();
cout << "Car Model?: ";
getline(cin, car1.model);
cout << "Car Year?: ";
cin >> car1.year;
cout << "Is the car electric?: ";
cin >> car1.isElectric;

控制台:

Enter information for Car 1.
Car Color?: Yellow
Car Model?: Model  S
Car Year?: 2020
Is the car electric?: true
Car Top Speed?: Enter information for Car 2.
Car Color?: Car Model?: Car Year?: Is the car electric?: Car Top Speed

输入bool值的默认方式是整数0(表示false(或1(表示true(。

要输入字符串"true",您需要使用std::boolalpha操纵器:

cin >> boolalpha >> car1.isElectric;

最新更新