首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于gets ( )的用法! 利用指针求字符数额

2013-02-18 
关于gets ( )的用法! 利用指针求字符数目下面这个程序我断点调试时,停在pstr 哪儿了?为什么啊?//输入一行

关于gets ( )的用法! 利用指针求字符数目
下面这个程序我断点调试时,停在p=str 哪儿了?为什么啊?

//输入一行文字,找出其中的字符各有多少?
# include <stdio.h>
int main ()
{
    int upper=0,lower=0,space=0,digit=0,other=0;
char str[256],*p;
printf ("input string:");
gets(str);
        p=str;                    //这里有问题吗? 
while (*p!='\0')
{
    if ((*p>'A')&&(*p<'Z'))
upper++;
else if ((*p>'a')&&(*p<'z'))
lower++;
else if (*p=' ')
space++;
else if ((*p>'0')&&(*p<'9'))
digit++;
else
other++;
}
printf ("upper case :%d\tlower case :%d\t",upper,lower);
printf ("space :%d\tdigit :%d\tother :%d",space,digit,other);

    return 0;
}

[解决办法]
你指出的地方没有问题,问题出在while内部没有p++,死循环了
[解决办法]
#include <stdio.h>
int main ()
{
    int upper=0,lower=0,space=0,digit=0,other=0;
    char str[256] = "\0",*p; //str 最好初始化

    printf ("input string:");
    gets(str);
        p=str;                    //这里有问题吗? 
    while (*p!='\0')
    {
        if ((*p>='A')&&(*p<='Z'))//1
            upper++;
        else if ((*p>='a')&&(*p<='z'))  //2
            lower++;
        else if (*p==' ')  //少了一个等号  建议再以后判断的时候这样写if(' ' == *p) 这样掉了一个等号编译器会报错
            space++;
        else if ((*p>='0')&&(*p<='9'))//1 2 3 范围有问题
            digit++;
        else
            other++;
p++; //判断一次之后p要往后移动
    }
    printf ("upper case :%d\tlower case :%d\t",upper,lower);
    printf ("space :%d\tdigit :%d\tother :%d",space,digit,other);
     
    return 0;
}

[解决办法]

//输入一行文字,找出其中的字符各有多少?
# include <stdio.h>
int main ()
{    
int upper=0,lower=0,space=0,digit=0,other=0;    
char str[256],*p;    
printf ("input string:");    
gets(str);       
 p=str;                    //这里有问题吗?     


while (*p!='\0')    
 {        
    if ((*p>'A')&&(*p<'Z'))            
      upper++;        
   else if ((*p>'a')&&(*p<'z'))            
      lower++;        
    else if (*p==' ')            
     space++;        
    else if ((*p>'0')&&(*p<'9'))           
     digit++;        
     else            
     other++;  
 
p++;  
 }    
 printf ("upper case :%d\tlower case :%d\t",upper,lower);   
  printf ("space :%d\tdigit :%d\tother :%d",space,digit,other);        
   return 0;
}


[解决办法]
while是个死循环。需要p++。,或者添加break条件语句。
[解决办法]
程序存在下列问题:
(1)while (*p !='\0') 改为 while (*p++ !='\0')
(2)判断大小写是应该是 >= 或者是 <=(3)判断空格是应该是 *p == ' ',不是 *p = ‘ ’

热点排行