以下是我的代码,当我输入" carol chen"时,我预计它将打印出9个字符,但它打印出10个。
您输入的名称是:carol chen
用户姓名中的字符数为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);
}
答案 0 :(得分:5)
只是不要通过添加排除and
条件中的空格的if
子句来计算空格:
试试这个:
if (name[i] != 0 && name[i] != ' ')
{
n += 1;
}
答案 1 :(得分:1)
这是一个更高效的版本
#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);
}