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
fgets( string, sizeof( string ), stdin );
or scanf like
scanf( "%99[^\n]", string );
The entered string can be less than the size of the array string. So this loop
for(i=0;i<100;i++)
invokes undefined behavior.
Instead you should use
for(i=0; string[i] != '\0'; i++)
It is better to rewrite the if statements like if-else statements
unsigned char c = string[i];
if( isalpha( c ) )
{
noAlpha++;
}
else if( isdigit( c ) )
{
noDigit++;
}
else if( ispunct( c ) )
{
noSpecial++;
}
So the output will look like
printf("Number of Alphabets in the string is %d\n", noAlpha);
printf("Number of Digits in the string is %d\n", noDigit);
printf("Number of Special characters in the string is %d\n", noSpecial);
#include<stdio.h>
#include<ctype.h>
int main(){
char string[100];
int i, noAlpha, noDigit, noSpecial;
printf("Input the string : ");
scanf( "%99[^\n]", string );
noAlpha=0;
noDigit=0;
noSpecial=0;
for(i=0; string[i] != '\0'; i++) {
unsigned char c = string[i];
if( isalpha( c ) )
{
noAlpha++;
}
else if( isdigit( c ) )
{
noDigit++;
}
else if( ispunct( c ) )
{
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.