Reputation: 41
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);
}
Upvotes: 1
Views: 2766
Reputation: 543
Here is a more efficient version
#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);
}
i = 0;
while ( (i < 80) && name[i]) {
if(name[i] != ' ') {
n += 1;
}
i++;
}
printf("\nThe number of characters in the user's name is %d\n", n);
free(name);
}
Upvotes: 1
Reputation: 1402
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;
}
Upvotes: 6