use of alphanumeric function c++, check if alphabet or digit from string
To check if a character in a string is an alphabet or a digit in C++, you can use the isalpha()
and isdigit()
functions from the <cctype>
library.
Here are the steps to check if a character is an alphabet or a digit in C++:
- Include the
<cctype>
library at the beginning of your code.
cpp
#include <cctype>
- Get the input string from the user or initialize it.
cpp
std::string input = "abc123";
- Iterate through each character in the input string using a loop.
cpp
for (char c : input) {
// Check if the character is an alphabet or a digit
}
- Use the
isalpha()
function to check if the character is an alphabet. It returns a non-zero value (true) if the character is an alphabet, and 0 (false) otherwise.
cpp
if (isalpha(c)) {
// Character is an alphabet
}
- Use the
isdigit()
function to check if the character is a digit. It returns a non-zero value (true) if the character is a digit, and 0 (false) otherwise.
cpp
if (isdigit(c)) {
// Character is a digit
}
- Handle the cases where the character is neither an alphabet nor a digit.
cpp
if (!isalpha(c) && !isdigit(c)) {
// Character is neither an alphabet nor a digit
}
- Repeat the above steps for each character in the input string.
Here is an example that puts it all together:
#include <iostream>
#include <cctype>
int main() {
std::string input = "abc123";
for (char c : input) {
if (isalpha(c)) {
std::cout << c << " is an alphabet." << std::endl;
}
else if (isdigit(c)) {
std::cout << c << " is a digit." << std::endl;
}
else {
std::cout << c << " is neither an alphabet nor a digit." << std::endl;
}
}
return 0;
}
This code will iterate through each character in the input
string and check if it is an alphabet or a digit using the isalpha()
and isdigit()
functions. It will then print the appropriate message based on the result.