Reputation: 29
I tried running this code and it seems that it will only check a character and not a whole string, if I have a long string like "Adam@", does anyone know how to check like the whole string and not just a character like 'n'.
char ch;
/* Input character from user */
printf("Enter any character: ");
scanf("%c", &ch);
/* Alphabet check */
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("'%c' is alphabet.", ch);
}
else if(ch >= '0' && ch <= '9')
{
printf("'%c' is digit.", ch);
}
else
{
printf("'%c' is special character.", ch);
}
Upvotes: 1
Views: 11931
Reputation: 26
scanf("%c", &ch);
This will only read a single character. To read an entire word, use:
char word[32]; // set size to the maximum word length you want to handle (+1 for null termination)
scanf("%31s", word);
Then use a loop to check every character in the word, such as:
for (int i = 0; i < 32; i++) {
if (char[i] == '\0') break;
// Check word[i]
...
}
Upvotes: 1
Reputation: 148965
C language has no direct notion of string. Only the Standard Library has: by convention, a character string is represented as a null terminated character array.
So you must:
declare an array large enough the hold the expected strings (say no more than 31 characters)
char word[32]; // 31 chars + 1 terminating null
read a (blank or space delimited) word taking care or not overflowing the array:
scanf("%31s", word);
loop over the characters of that word:
for (int i=0; i<strlen(word); i++) {
char ch = word[i];
// copy here your current code processing ch
}
Upvotes: 2
Reputation: 21
As you would have to use a char array to store this string, you can easily iterate over this array.
Just like htis:
char s[100]; //string with max length 100
/* Input string from user */
printf("Enter any string: ");
scanf("%s", &s);
/* Alphabet check */
for(int i = 0; i <100; i++){
char ch = s[i];
if(ch == '\0') break; //stop iterating at end of string
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("'%c' is alphabet.", ch);
}
else if(ch >= '0' && ch <= '9')
{
printf("'%c' is digit.", ch);
}
else
{
printf("'%c' is special character.", ch);
}
}
Upvotes: 1