【问题标题】:Writing a program in C++ that asks the user to enter values for all primitive types in C++用 C++ 编写一个程序,要求用户在 C++ 中输入所有原始类型的值
【发布时间】:2020-02-16 20:58:44
【问题描述】:

我开始学习 C++,我正在尝试创建一个程序,要求用户为 C++ 中的所有原始类型添​​加值,这是我目前所写的:

#include <iostream>
using namespace std;

int main()
{
 bool empty_bool;
 char empty_char;
 int empty_int;
 float empty_float;
 double empty_double;
 cout << "Please enter a value for all inbuilt primitive types in C++" << endl;
 cout << "Boolean:";
 cin >> empty_bool;
 cout << "Char";
 cin >> empty_char;
 cout << "Int";
 cin >> empty_int;
 cout << "float";
 cin >> empty_float;
 cout << "double";
 cin >> empty_double;
}

问题是我的程序接受了布尔值的输入,但它只打印了其余的变量名,但它不允许获取所述变量的值,我不知道为什么,什么是我在这里做错了吗?

【问题讨论】:

  • 你写了true之类的东西作为布尔值的输入吗?那是行不通的。您需要输入0(为假)或1(为真)。
  • 布尔值输入什么?除非设置了boolalpha 标志(默认情况下未设置),否则cin &gt;&gt; empty_bool 需要输入中的整数,并将零解释为false,非零解释为true
  • 在 C++ 中,bool 在内部是一个整数值。所以你必须输入 1 为真,0 为假。
  • 是的,我输入的是 true,而不是 1 或 0,来自 JavaScript 背景,我没想到,谢谢!
  • @IgorTandetnik 我的 GCC 只接受 01,没有其他数字作为 bool 的输入(使用 std::noboolalpha

标签: c++


【解决方案1】:

在进行任何输入后,cin 将包含一个结果条件。读取无效输入会将输入流cin 置于fail 状态;通常,您应该通过在布尔上下文中评估 cin 来检查:

if (cin >> empty_int)
    cout << empty_int; // empty_int here is not empty anymore
else
    cout << "error";

当读取 bool 的格式不正确的值时(如 cmets 中所述,它必须为 0 或 1 或 truefalse,具体取决于 boolalpha 标志),cin 会记住其错误状态,并且不会做任何进一步的输入until it is reset:

cin.clear();

user4581301 的注释:

请注意,clear 不会从流中删除违规数据。根据读取的内容以及失败之前的方式,您可能在流中有些东西会再次导致完全相同的错误。如果是这样,请在继续之前将其删除,使用以下方法之一:

  • 使用std::istream::ignore(如here
  • 将其读入诸如std::string 之类的许可文件中
  • 或任何最适合您的使用方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    相关资源
    最近更新 更多