check digit in string c++ code example
Example 1: check if character in string is digit c++
int main() {
char val1 = 's';
char val2 = '8';
if(isdigit(val1))
printf("The character is a digit\n");
else
printf("The character is not a digit\n");
if(isdigit(val2))
printf("The character is a digit\n");
else
printf("The character is not a digit");
return 0;
}
Example 2: c++98 check if character is integer
std::string s = "1234798797";
std::istringstream iss(s);
int num = 0;
if (!(iss >> num).fail()) {
std::cout << num << std::endl;
}
else {
std::cerr << "There was a problem converting the string to an integer!" << std::endl;
}
Example 3: c check if char is number
char c = 'a'; // or whatever
if (isalpha(c)) {
puts("it's a letter");
} else if (isdigit(c)) {
puts("it's a digit");
} else {
puts("something else?");
}