gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:44:15 24 4
gpt4 key购买 nike

我已经尝试了这段代码的几种不同变体,但似乎无法正确使用。我对 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com