简体   繁体   中英

C++ Function Not Converting Decimal Point as Part of the Number (Input Validation)

How can I modify this function so that it includes a decimal place as part of the inputted numerical value if the decimal is not the first position of the input? Realistically speaking, the number should have one decimal place which can either be the first position (index[0]) or any other position in the number. For example, if I input 7.3, it should return back 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 , so if you are just trying to get it working, ReadDouble can just execute atof:

double ReadDouble(string prompt)
{
    string input;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM