使用C中的switch语句计算字符串中出现的空格,逗号和点

时间:2018-11-10 13:42:13

标签: c

#include <stdioh.>
#include <string.h>
int main()
{
char a[100];
int i,contor=0;
printf("Introduceti sirul: ");
gets(a);
switch(a)
{
case ',':
    contor++;
    break;
case '.':
    contor++;
    break;
case ' ':
    contor++;
    break;
default:
    printf("Nu exista spatii,virgule sau puncte.");
}
printf("Numarul de spatii, virgule si puncte este: %d",contor);
return 0;
}

我在这里尝试过,但是给了我一个错误-开关数量不是整数
     有人帮忙吗?:))我无法解决

2 个答案:

答案 0 :(得分:0)

switch(a)将不起作用,因为a是一个数组(衰减为指向char的指针)。您可能想要类似的东西:

    char *cp= a;
    while (*cp)
    {
        switch(*cp)
        {
            case ',':
                    contor++;
                    break;
            // etc
        }
        cp++;
    }

答案 1 :(得分:0)

switch(expression) {
   case constant-expression  :
...
   default : //Optional
      statement(s);
}
  

switch语句中使用的表达式必须具有整数或   枚举类型,或属于类类型,其中该类具有单个   将函数转换为整数或枚举类型。

换句话说,您不能使用整个输入字符串作为switch语句的表达式。上面的Paul Ogilvie给出了一个完美的示例。