我正在嘗試只接受程序中用戶的數字輸入。我做了很多研究,但是給出的所有示例代碼仍然可以接受輸入,比如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”函數。
那么,有沒有哪種方法只接受純數字,還包括小數點?
https://godbolt.org/z/75efEP9Y8