如何解决C ++函数未将小数点转换为数字的一部分输入验证
如果小数位不是输入的第一位,如何修改此函数,使其在输入的数值中包含小数位?实际上,数字应该有一个小数位,可以是第一个位置(索引[0])或数字中的任何其他位置。例如,如果我输入7.3,它应该返回7.3。
#include <iostream>
#include <cmath>
#include <climits>
#include <string>
using namespace std;
double ReadDouble(string prompt)
{
string input;
string convert;
bool isValid=true;
do {
isValid = true;
cout << prompt;
cin >> input;
if (isdigit(input[0]) == 0 && input[0] != '.' && input[0] != '+' && input[0] != '-' && input[0] != '+')
{
cout << "Error! Input was not a number.\n";
}
else
{
convert = input.substr(0,1);
}
long len = input.length();
for (long index = 1; index < len && isValid == true; index++)
{
if (isdigit(input[index]) == 0){
cout << "Error! Input was not an integer.\n";
isValid=false;
}
else if (input[index] == '.') {
;
}
else {
convert += input.substr(index,1);
}
}
} while (isValid == false);
double returnValue=atof(convert.c_str());
return returnValue;
}
int main()
{
double x = ReadDouble("Enter a value: ");
cout << "Your value: " << x << endl;
return 0;
}
解决方法
atof does what you need already,因此,如果您只是想使其正常运行,ReadDouble可以执行atof:
double ReadDouble(string prompt)
{
string input;
cout << prompt;
cin >> input;
return atof(input);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。