以前寫過了Python如何判斷輸入字符串是否爲數字,可是Python是弱類型語言,相比之下C++這種強類型語言斷定難度更大。html
例如,我要把不斷輸入的字符串中數字都轉爲double類型,別的都保存爲字符串。那麼我接收輸入的數據類型只能爲string。git
C++和Python同樣提供了isdigit()的方法,可是isdigit()只能判斷一個字符,且只能一位一位判斷,也就是說只能判斷一個字符是否是0~9之間的整型數。連負數都沒法判斷。函數
好在C++11在string類中,提供了stoi, stod, stof, stol, stoll等函數分別是把字符串轉化爲int, double, float, long, long long型。code
那麼,思路就和Python中同樣了,利用異常捕捉。htm
bool isdouble(string x) { double y; try{ y = stod(x); } catch (const std::exception&){ return false; } return true; }
同理,原理是stod()這個函數,沒法將非數字的變量轉換爲double。blog