数字を確認したい場合は、これを試すことができます:
std::string str = "";
std::cout<<"enter string>>";
std::cin>>str;
int is_number = 0;
char filter[] = "0123456789";
for(int n=0; n<str.size(); ++n){
for(int i=0; i<10; ++i){
if(str[n] == filter[i]){
++is_number;
break; // found match, filter next char in str
}else if(str[n] != filter[i] && i == 9){
std::cout<<"'"<<str[n]<<"' is not a digit!\n";
}
}
}
if(is_number == str.size()){
std::cout<<"You entered a number";
}else std::cout<<"You didn't enter a number!";
または、10進数を認識するために、これを試すことができます:
int is_number = 0, is_decimal = 0;
char filter[] = ".0123456789";
for(int n=0; n<str.size(); ++n){
for(int i=0; i<11; ++i){
if(str[n] == filter[i]){
if(filter[i] == '.'){
++is_decimal;
}
++is_number;
break;
}
}
}// for decimal
if(is_number == str.size() && is_decimal <= 1){
std::cout<<"You entered a number";
}else std::cout<<"You didn't enter a number!";