I'm just not sure how to use isalpha() in if() to check if an entire string is comprised of letters. Thanks!
2 Answers
Isalpha takes as an argument a character, it is easy to use a for loop to iterate over each character in a string:
string name = "my name"; // char* name
for( int k = 0, s = strlen (name); k < s; k++)
{
if( isalpha (name[ k ] )) // if( !salpha(name[k])) If it is not
{
code...
}
}
The function isalpha()
takes a character as an argument to the function and returns true if character is alphabetic and false otherwise, which thus becomes condition for an statement if(condition)
, so you can simply use a for loop to iterate over each character in a string and check using if condition, is the ith character in a string an alphabetical letter or not. And be sure to include library ctype.h
. Example as follows:
#include <ctype.h>
...
string word = get_string();
for (int i = 0, n = strlen(word); i < n; i++)
{
if (isalpha(word[i])) // here condition is checked is it alphabetical letter for each character in string
{
// code...
}
else
{
// otherwise code...
}
}