【问题标题】:checking if entered value is float, clearing cin检查输入的值是否为浮点数,清除 cin
【发布时间】:2014-05-21 17:07:45
【问题描述】:

我尝试了此代码的几种不同变体,但似乎无法正确使用。我对 c++ 还很陌生,所以这可以解释它。此代码是一个简单计算器的一部分。它基本上要求用户输入两个数字(它们可以是浮点数),然后要求用户输入数学运算符,然后进行运算。如果用户输入的不是数字,然后在 if 语句中要求再次输入数字时输入数字,控制台将打印“-9.25596e+061”。这是代码:

#include "stdafx.h"
#include <iostream>
#include <cctype>
using namespace std;

double getUserInput()
{
    //Make double, assign double, return double if number
    double dUserInput;

    //checks if it failed to cin
    if (!(cin >> dUserInput))
    {
        //statement is true
        cin.clear();
        cin.ignore(99999, '\n');
        cout << "You did not enter a number, please try again: ";
        getUserInput();
    }else
        //statement if false
    cout << "Number entered"; //for debugging purposes
    return dUserInput;
}

【问题讨论】:

  • 我看不到你在哪里打印值。
  • 你区分带小数点和不带小数点的数字吗?例如,数字 2 可以是 doubleint

标签: c++ double cin


【解决方案1】:

您错过了在对getUserInput 的递归调用中添加return

换行

    getUserInput();

    return getUserInput();

更新

您可以将函数更改为非递归版本。

double getUserInput()
{
    //Make double, assign double, return double if number
    double dUserInput;

    //checks if it failed to cin
    while (!(cin >> dUserInput))
    {
        cin.clear();
        cin.ignore(99999, '\n');
        cout << "You did not enter a number, please try again: ";
    }

    cout << "Number entered"; //for debugging purposes
    return dUserInput;
}

【讨论】:

  • 正确。但同样值得注意的是,递归在这里可能不是一个好主意。
  • @LightnessRacesinOrbit 感谢您的建议。更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多