【问题标题】:Why isn't the bool member in struc not taking the user input?为什么 struc 中的 bool 成员不接受用户输入?
【发布时间】:2021-02-03 01:15:15
【问题描述】:

我正在创建一个名为 struct Car 的函数,它接受几个成员值的用户输入(在 int main 中)。其中一个成员是 bool (isElectric),但我似乎无法弄清楚为什么在我输入“true”或“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

【问题讨论】:

  • 尝试输入 1 和 0 作为布尔值,看看会发生什么,希望这有助于理解布尔值

标签: c++ struct boolean user-input


【解决方案1】:

输入bool 值的默认方式是整数0(表示假)或1(表示真)。

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

cin >> boolalpha >> car1.isElectric;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2020-09-26
    • 1970-01-01
    • 2016-03-05
    • 2020-05-13
    相关资源
    最近更新 更多