注册 登录
编程论坛 VC++/MFC

输入结果不与要求不符

沧声笑 发布于 2010-09-29 22:26, 457 次点击
#include<iostream>
using namespace std;
int main()
{
    int m=0,n=0,p=0,b=0,i=1;
    char a[10];
    gets(a);
    while(a[i]!='\0')
    {
        if((a[i]>=65&&a[i]<=90)||(a[i]>=97&&a[i]<=122))
            m++;
        else    if(a[i]>=48&&a[i]<=57)
            n++;
           
        else    if(a[i]=' ')
            p++;
        else
            b++;
        i++;
    }
   
    cout<<"字母有:"<<m<<"数字有:"<<n<<"空格有:"<<p<<"其他字符有:"<<b<<endl;
}
5 回复
#2
沧声笑2010-09-29 22:27
忘了补充了,题目是 输入一串字符。要求输出 其中字符有,数字有,空格有,其他字符有多少个
#3
m21wo2010-09-29 23:12
程序代码:
#include<iostream>

using namespace std;
int main()
{
    int m=0,n=0,p=0,b=0,i=0;
    char a[100];
    gets(a);
    while(a[i]!='\0')
    {
        if((a[i]>='A'&&a[i]<='Z')||(a[i]>='a'&&a[i]<='z'))
            m++;
        else    if(a[i]>='0'&&a[i]<='9')
            n++;
         
        else    if(a[i]=' ')
            p++;
        else
            b++;
        i++;
    }
   
    cout<<"字母有:"<<m<<"数字有:"<<n<<"空格有:"<<p<<"其他字符有:"<<b<<endl;

}

 

把i的初值0改为1 就好了!



#4
聋眼睛瞎耳朵2010-09-29 23:56
#include<iostream>
using namespace std;
int main()
{
    int m=0,n=0,p=0,b=0;
    char temp;
    while((temp=cin.get())!='\n')
    {
        if((temp>=65&&temp<=90)||(temp>=97&&temp<=122))
            m++;
        else   
        {
            if(temp>=48&&temp<=57)
                n++;
            else
            {
                if(temp==' ')
                    p++;
                else
                    b++;
            }
        }
    }
    cout<<"字母有:"<<m<<"数字有:"<<n<<"空格有:"<<p<<"其他字符有:"<<b<<endl;
}

你上面定义了一个长度为10的字符数组,输入时很容易超出而产生错误;这种方式不好!而且你上面做空格判断时,用的是‘=’而不是‘==’;这是非常严重的错误!我给你简单改了一下,你看看!
#5
沧声笑2010-09-30 20:53
回复 3楼 m21wo
谢谢指教,非常感谢
#6
沧声笑2010-09-30 20:53
回复 4楼 聋眼睛瞎耳朵
谢谢指导,受益匪浅,谢谢
1