Yotta Lynn Yotta Lynn - 3 months ago 7
C Question

how to count the number of characters and ignore space in C

Following is my code, when I enter "carol chen", I expect it will print out 9 characters, but it print out 10.

The name you enter is: carol chen

The number of characters in the user's name is 10

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){

char *name;
int i;
int n = 0;

name= (char *)calloc(80, sizeof(char));

if(name == NULL) {

printf("\nOut of memory!\n");
return 1;
}
else {

printf("The name you enter is: ");
scanf("%79[0-9a-zA-Z ]", name);

for(i=0; i<80; i++){

if(name[i] != 0){

n += 1;
}
}

printf("\nThe number of characters in the user's name is %d\n", n);

}

free(name);

}

Answer

Just don't count the spaces by adding an and clause that excludes spaces inside your if condition:

Try this:

if (name[i] != 0 && name[i] != ' ')
{
    n += 1;
}
Comments