あなたはstring
はのみ数と(空白を除く)他には何が含まれているかどうかを確認したい場合は、この使用:
#include <sstream>
bool is_numeric (const std::string& str) {
std::istringstream ss(str);
double dbl;
ss >> dbl; // try to read the number
ss >> std::ws; // eat whitespace after number
if (!ss.fail() && ss.eof()) {
return true; // is-a-number
} else {
return false; // not-a-number
}
}
を
ss >> std::ws
は、このような空白末尾に数字を受け入れるために重要です"24 "
となります。
ss.eof()
のチェックは、"24 abc"
のような文字列を拒否する場合に重要です。これは、数字(および空白)を読み取った後に文字列の最後に到達することを保証します。
テストハーネス:
#include <iostream>
#include <iomanip>
int main()
{
std::string tests[8] = {
"", "XYZ", "a26", "3.3a", "42 a", "764", " 132.0", "930 "
};
std::string is_a[2] = { "not a number", "is a number" };
for (size_t i = 0; i < sizeof(tests)/sizeof(std::string); ++i) {
std::cout << std::setw(8) << "'" + tests[i] + "'" << ": ";
std::cout << is_a [is_numeric (tests[i])] << std::endl;
}
}
出力:
'': not a number
'XYZ': not a number
'a26': not a number
'3.3a': not a number
'42 a': not a number
'764': is a number
' 132.0': is a number
'930 ': is a number
"12.5 ABC" "文字列が数値である" としての資格していますか? 「いいえ」の場合、これまでの回答は一切適用されません。 – etarion