c++ - 检查输入值是否为 float ,清除 cin

标签 c++ double cin

我尝试了此代码的几种不同变体,但似乎无法正确执行。我对 C++ 还很陌生,所以这可以解释它。此代码是一个简单计算器的一部分。它基本上要求用户输入两个数字(它们可以是 float ),然后要求用户提供数学运算符,然后进行运算。如果用户输入的不是数字,然后在 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;
}

最佳答案

您错过了在对 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;
}

关于c++ - 检查输入值是否为 float ,清除 cin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23789696/

相关文章:

c++ - 如何在 CPP 中使用 "GetExitCodeProcess"、 "CreateProcess"和 "WaitForSingleObject"功能?

c++ - 从 vector 切换到双端队列的大小限制通常是多少?

C++ 将静态二维 double 组转换为 double **

c++ - 如何在 while 循环中使用 cin?

c++ - 枚举及其值

objective-c - Delphi double 型到 Objective C double 型

ios - 根据第一个非零将数字舍入到最接近的 "nth"

C++ - 你如何在用户输入后循环?

c++ - Cin 在 for 循环中使用后被跳过

c++ - WxButton - 鼠标悬停和边框大小