【问题标题】:C++ Function Not Converting Decimal Point as Part of the Number (Input Validation)C++ 函数不将小数点转换为数字的一部分(输入验证)
【发布时间】: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


【解决方案1】:

atof does what you need already,所以如果你只是想让它工作,ReadDouble 可以直接执行 atof:

double ReadDouble(string prompt)
{
    string input;

    cout << prompt;
    cin >> input;
    return atof(input);
}

【讨论】:

    猜你喜欢
    • 2012-09-29
    • 2019-12-02
    • 1970-01-01
    • 2011-10-29
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    相关资源
    最近更新 更多