Just write a function that will perform such a check.
It can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
#include <ctype.h>
int is_all_alpha( const char *s )
{
while ( *s && isalpha( ( unsigned char )*s ) ) ++s;
return *s == '';
}
int main(void)
{
char *s1 = "Hello";
char *s2 = "2021";
printf( ""%s" is %sa valid word
", s1, is_all_alpha( s1 ) ? "" : "not " );
printf( ""%s" is %sa valid word
", s2, is_all_alpha( s2 ) ? "" : "not " );
return 0;
}
The program output is
"Hello" is a valid word
"2021" is not a valid word
Or using the definition of the name string
the program can look like
#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
int is_all_alpha( string s )
{
while ( *s && isalpha( ( unsigned char )*s ) ) ++s;
return *s == '';
}
int main(void)
{
string s1 = "Hello";
string s2 = "2021";
printf( ""%s" is %sa valid word
", s1, is_all_alpha( s1 ) ? "" : "not " );
printf( ""%s" is %sa valid word
", s2, is_all_alpha( s2 ) ? "" : "not " );
return 0;
}
Though it is much better to declare the function parameter as having the type const char *
instead of string
because within the function is_all_alpha
the pointed string is not changed. And the type const string
is not the same as the type const char *
. The type const string
is an alias for the type char * const
that is it means that the passed pointer itself is constant not the string pointed to by the pointer.
Instead of the conditional operator used in the calls of printf you can use if-else statements. For example
if ( is_all_alpha( text ) )
{
// all symbols of text are letters
// do something
}
else
{
// text contains a non-alpha symbol
// do something else
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…