张三ccccccc 发表于 2021-8-10 13:33:08

字符串和指针

/****题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。****/
#include "stdio.h"
intmain()
{
        char str,*p;
        int letters=0,space=0,digit=0,others=0;
        printf("Please input character:\n");
        scanf("%s",&str);
        p=&str;
        while ((*p++)!='\0')/****原代码没有用指针,只是再while语句加了判断条件(str=getchar()!='\n';)****/
        {
                if(str>='A'&&str<='Z'||str>='a'&&str<='z')
                {
                        letters++;
                }
                else if(str==' ')
                        {
                                space++;
                        }
                else if(str>='0'&&str<='9')
                {
          digit++;
                }
                else
                        others++;
                }
        printf("%d %d %d %d",letters,space,others,digit);
        }
/*****我这样写的话,问题出在哪里了,求大佬解答一下,跪谢******/

wp231957 发表于 2021-8-10 13:40:58

char str这是单字符,无法容纳字符串

张三ccccccc 发表于 2021-8-10 13:48:38

wp231957 发表于 2021-8-10 13:40
char str这是单字符,无法容纳字符串

那那那那getchar()函数不是一次只能输入一个字符,这个题目用getchar()为啥能输入一段字符串,赋值给str。/跪谢/

wp231957 发表于 2021-8-10 14:24:35

张三ccccccc 发表于 2021-8-10 13:48
那那那那getchar()函数不是一次只能输入一个字符,这个题目用getchar()为啥能输入一段字符串,赋值给 ...

#include "stdio.h"
intmain()
{
    char str={'\0'};
    char *p=str;
    int letters=0,space=0,digit=0,others=0;
    printf("Please input character:\n");
    scanf("%[^\n]",p);
    while (*p!='\0')
    {
            if((*p>='A' && *p<='Z') || (*p>='a' && *p<='z'))
            {
                letters++;
            }
            else if(*p==' ')
            {
                space++;
            }
            else if(*p>='0' && *p<='9')
            {
                digit++;
            }
            else
                others++;
            p++;
    }
    printf("字符=%d空格=%d 其他=%d 数字=%d \n",letters,space,others,digit);
}
页: [1]
查看完整版本: 字符串和指针