首页 > 解决方案 > 数数 C 编程中字符串中的单词数(我收到空字符常量错误)

问题描述

我的代码是不计算字符串中的单词。但是 (a[i]=='') 显示空字符常量错误

#include <stdio.h>

int main() {

    char a[20];

    int i,c1=0,c2=0;

    scanf("%[^\n]",a);

    for(i=0;a[i]!='\0';i++)
    {
        c1++;

        if(a[i]=='')

        c2++;
    }
    printf("%d\n",c1);

    printf("%d",c2+1);

    return 0;
}

对于输入 - 汤姆在这里

我希望输出为 -11 3

编译错误-在函数'main'中:

prog.c:10:15:错误:空字符常量 if(a[i]=='') ^

标签: c

解决方案


#include <stdio.h>

int main() {

    char str[50];

    int i, numberOfWords=0;

    gets(str);

    for(i=0; str[i]!='\0'; i++) {
        if(str[i] == 32) //ascii code of space is 32
            numberOfWords++;
    }
    printf("number of words = %d\n", numberOfWords + 1);
    //adding 1 to numberOfWords because if there are two words, there will be 2-1=1 space between them. eg= "Hello World"

    return 0;
}

推荐阅读