僅接受用戶的數字輸入

我正在嘗試只接受程序中用戶的數字輸入。我做了很多研究,但是給出的所有示例代碼仍然可以接受輸入,比如10abc

這是一個英尺到米的轉換器。

include <iostream>
using namespace std;

bool isNumber(string feet){
    for (int i = 0; i < feet.length(); i++){
        if (isdigit(feet[i]) == false){
            return false;
        }
    return true;
    }
}

int main(){
    string feet;
    beginning:
    cout << "Enter the feet: ";
    cin >> feet;

    if (isNumber(feet))
        cout << "The meter is: " << (double)stod(feet) * 0.3048 << endl;
    else {
        cout << "Invalid input. Please try again" << endl;
        goto beginning;
    }
    return 0;
}

這段代碼近乎完美,但它不接受小數點(無言面),因為小數點會破壞“isdigit”函數。

那么,有沒有哪種方法只接受純數字,還包括小數點?

? 最佳回答:
template <typename T>
T readFromLine(std::istream& in)
{
    std::string line;
    while (std::getline(in, line)) { // read whole line until it is possible
        std::istringstream line_stream { line }; // initialize string stream to parse line read
        T x;

        // try read `x` then discard white spaces then check if end of lien was reached
        if (line_stream >> x >> std::ws && line_stream.eof()) {
            // stop since reading was successful and line do not contain anything extra
            return x;
        }
        // continue if reading `x` was unsuccessful or when line contains something extra
    }
    // while loop ended since end of file was reached or error on input stream
    throw std::invalid_argument { "stream to short" };
}

https://godbolt.org/z/75efEP9Y8

主站蜘蛛池模板: 国产熟女一区二区三区五月婷| 久久国产一区二区| 亚洲成AV人片一区二区| 亚洲av无码成人影院一区| 国产成人精品一区二区三区无码| 亚洲AV无码一区二区三区牲色| 国产另类TS人妖一区二区 | 日本道免费精品一区二区| 无码国产精品一区二区免费I6| 天堂国产一区二区三区| 国产激情无码一区二区| 中文字幕精品亚洲无线码一区| 久久无码精品一区二区三区| 精品一区二区三区无码视频| 日美欧韩一区二去三区 | 久久中文字幕一区二区| 亚洲视频在线一区二区| 一区二区三区日本视频| 内射白浆一区二区在线观看 | 国产成人无码aa精品一区| 免费一本色道久久一区| 成人h动漫精品一区二区无码| 蜜桃AV抽搐高潮一区二区| 国产精品无码一区二区在线观| 麻豆AV无码精品一区二区 | 亚洲日韩AV一区二区三区四区| 精品无码一区二区三区亚洲桃色| 无码少妇一区二区| 日韩精品无码一区二区三区免费| 亚洲AV无码一区二区三区DV| 国产精品无圣光一区二区| 亚洲AV美女一区二区三区| 日韩精品无码一区二区三区| 人妻无码一区二区不卡无码av | 中文字幕人妻丝袜乱一区三区| 中文字幕一区二区人妻性色| 免费日本一区二区| 国产精品视频分类一区| 午夜视频一区二区三区| 国产福利一区二区在线视频| 国模吧无码一区二区三区|