首页 > 解决方案 > C程序读取两个'*'之间的字符

问题描述

我希望程序读取两颗星之间的字符,如果没有两颗星,它必须打印相应的消息。例如,如果输入是1abc*D2Efg_#!*34567,输出是between first tow stars (letters : 4, digits:1, other:3)任何帮助将不胜感激

int main()
{
  int ch,lowercase_lett,digits,other,uppercase_lett,asterisk;
  lowercase_lett = 0;
  uppercase_lett = 0;
  digits = 0;
  other = 0;
  asterisk = 0;
  printf("enter characters : ");
  while((ch = getchar()) != '\n' && ch != EOF)
  {
    if(ch == '*')
    {
      asterisk++;
    }
    if(asterisk < 2)
    {
      printf("\ntwo asterisks not found\n");
    }
    else
    {
      if(ch>='a' && ch <= 'z')
      {
        lowercase_lett++;
      }
      else if(ch>='A' && ch <= 'Z')
      {
        uppercase_lett++;
      }
      else if(ch >='0' && ch <= '9')
      {
        digits++;
      }
      else
      {
        other++;
      }
    }
  }
  printf("\n%d letters %d digits and %d other" , lowercase_lett+uppercase_lett,digits,other);
  return 0;
}

标签: c

解决方案


当恰好找到一个星号时计数字符。中的函数ctype.h可用于确定字符的类型。

#include <stdio.h>
#include <ctype.h>

int main(void){
    int ch,lowercase_lett,digits,other,uppercase_lett,asterisk;
    lowercase_lett = 0;
    uppercase_lett = 0;
    digits = 0;
    other = 0;
    asterisk = 0;
    printf("enter characters : ");
    while((ch = getchar()) != '\n' && ch != EOF)
    {
      if(ch == '*')
      {
        asterisk++;
        if(asterisk>=2)
        {
          break;
        }
      }
      else if(asterisk==1)
      {
        if(islower(ch))
        {
            lowercase_lett++;
        }
        else if(isupper(ch))
        {
            uppercase_lett++;
        }else if(isdigit(ch)){
            digits++;
        }else{
            other++;
        }
      }
    }
    if(asterisk<2)
    {
      printf("\ntwo asterisks not found\n");
    }
    else
    {
      printf("\n%d letters %d digits and %d other" , lowercase_lett+uppercase_lett,digits,other);
    }
    return 0;
}

推荐阅读