gpt4 book ai didi

c++ - 有没有一种方法可以在C++中将 'char**'转换为 'double'?

转载 作者:行者123 更新时间:2023-12-03 07:06:59 24 4
gpt4 key购买 nike

我试图将用户输入执行限制为仅数字,当他们输入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;
}
}

最佳答案

以下代码要求获得 double 数,直到获得有效的 double 数。

它使用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;

}

关于c++ - 有没有一种方法可以在C++中将 'char**'转换为 'double'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60003395/

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