【发布时间】:2020-10-08 17:50:20
【问题描述】:
如果小数点不是输入的第一个位置,我该如何修改此函数,使其包含一个小数位作为输入数值的一部分?实际上,数字应该有一个小数位,可以是第一个位置(索引 [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;
}
【问题讨论】:
-
与你的问题无关,但更喜欢
convert += input[index];而不是构建一个字符的子字符串。 -
您必须手动完成还是只想让它工作? ...为什么要验证浮点输入并要求它是整数?你想要
double还是整数? -
我必须手动完成,即使此时我只想让它工作
-
你知道
atoi返回一个int,对吧?也许您正在寻找atof。 -
strtol()/stoi()提供比atoi()更多的错误检查潜力。
标签: c++ validation for-loop input floating-point