c++ check if string contains non alphanumeric
Sure! Here is an example of how you can check if a string contains non-alphanumeric characters in C++:
#include <iostream>
#include <string>
#include <cctype>
bool containsNonAlphanumeric(const std::string& str) {
for (char c : str) {
if (!std::isalnum(c)) {
return true;
}
}
return false;
}
int main() {
std::string input;
std::cout << "Enter a string: ";
std::cin >> input;
if (containsNonAlphanumeric(input)) {
std::cout << "The string contains non-alphanumeric characters." << std::endl;
} else {
std::cout << "The string does not contain non-alphanumeric characters." << std::endl;
}
return 0;
}
Explanation of the code:
- The
containsNonAlphanumeric
function takes astd::string
as input and returns a boolean value indicating whether the string contains non-alphanumeric characters. - The function uses a
for
loop to iterate through each character in the string. - Inside the loop, the
std::isalnum
function is used to check if the character is alphanumeric. If it is not alphanumeric, the function returnstrue
immediately. - If the loop completes without finding any non-alphanumeric characters, the function returns
false
. - In the
main
function, the user is prompted to enter a string. - The
containsNonAlphanumeric
function is called with the input string, and the result is used to determine whether the string contains non-alphanumeric characters. - Finally, a message is printed to the console indicating whether the string contains non-alphanumeric characters or not.
I hope this helps! Let me know if you have any further questions.