我试图将用户输入的执行限制为仅数字,当他们输入 a / b 而不是 8 / 2 时,结果为零,但是当他们尝试输入这样的内容时,我想给他们一个警告。当我执行我的代码时,我收到无法转换char**为double赋值的错误。我为转换实现的字符是numvalidation验证用户输入的第一个值,如果输入是数字,则接受否则返回默认消息。
#include <iostream>
using namespace std;
int main()
{
char * numvalidation;
double var1, var2;
beginning:
cout << "Enter the First value: ";
cin >> var1;
cout << "Enter the second value: ";
cin >> var2;
if (var1 != '\0')
{
var1 = (&numvalidation);
if (*numvalidation != '\0')
{
cout << "First Value was not a number,Try again with a correct value." << endl;
}
{
cout << "Do you want to continue using the Calculator? (Y/N)" << endl;
char restart;
cin >> restart;
if (restart == 'y' || restart == 'Y')
goto beginning;
}
}
cout << "What do you want to do?" << endl;
cout << "+ :Addition is available" <<endl;
cout << "- :Subtraction is available" <<endl;
cout << "* :Multiplication is available" <<endl;
cout << "/ :Division is available" <<endl;
cout << "Please chose one of the option below" <<endl;
char decision;
cout << "Decision: ";
cin >> decision;
system ("cls");
switch (decision)
{
case '+':
cout << var1 << " + " << var2 << " = " << "" << ( var1 + var2 ) <<endl;
break;
case '-':
cout << var1 << " - " << var2 << " = " << "" << ( var1 - var2 ) <<endl;
break;
case '*':
cout << var1 << " * " << var2 << " = " << "" << ( var1 * var2 ) <<endl;
break;
case '/':
if (var2 == !0)
cout << var1 << " / " << var2 << " = " << "" << ( var1 / var2 ) <<endl;
else
cout << "The value you have entered is invalid because you cannot divide any number by zero " <<endl;
break;
default:
cout << "You have not entered the correct data";
}
{
cout << "Do you want to continue using the Calculator? (Y/N)" << endl;
char decision2;
cin >> decision2;
if (decision2 == 'y' || decision2 == 'Y')
goto beginning;
}
}
Run Code Online (Sandbox Code Playgroud)
下面的代码要求一个双精度直到它得到一个有效的双精度。
它使用std::string. 您只能使用,isdigit()但这会很荒谬(在我看来)。
#include<string>
#include<iostream>
#include<cctype>
int main(){
double var1{};
std::string temp{};
size_t processed_chars_no{};
do{
std::cout<<"Enter a valid double value: \n";
std::cin >> temp;
if( isdigit(temp[0]) )var1 = std::stod( temp, &processed_chars_no );
}
while ( processed_chars_no != temp.size() );
std::cout<<"\n"<<var1;
}
Run Code Online (Sandbox Code Playgroud)