So here is my code and I am struggling with the ispunct(); it starts counting in 8 and in isalpha() it starts counting in 1 so I print it noAlpha-1, but in ispunct() it is awkward to put noSpecial-8 to become accurate. I don't have any issues in digits. What might be the problem here?
#include<stdio.h>
#include<ctype.h>
int main(){
char string[100];
int i, noAlpha, noDigit, noSpecial;
printf("Input the string : ");
gets(string);
noAlpha=0;
noDigit=0;
noSpecial=0;
for(i=0;i<100;i++) {
if(isalpha(string[i]))
noAlpha++;
if(isdigit(string[i]))
noDigit++;
if(ispunct(string[i]))
noSpecial++;
}
printf("Number of Alphabets in the string is %d\n", noAlpha-1);
printf("Number of Digits in the string is %d\n", noDigit);
printf("Number of Special characters in the string is %d\n", noSpecial);
}
The function gets is unsafe and is not supported by the C Standard.
Either use fgets like
or scanf like
The entered string can be less than the size of the array string. So this loop
invokes undefined behavior.
Instead you should use
It is better to rewrite the if statements like if-else statements
So the output will look like