是小狐狸啊 2016-05-02 04:27 采纳率: 63.6%
浏览 1302
已采纳

C++ 字符计算时遇到的问题

//输入一行文字,找出其中大写字母、小写字母、空格、数字、及其他字符各有多少。
//嫌麻烦,我没有定义函数,也没有用指针,这个程序错哪了??
int main(int argc, char * argv[])
{
int upper=0,lower=0,digit=0,space=0,other=0,i=0;
char s[20];
cout<<"Input string:";

for( i=0;i {
cin>>s[i];
}
for(int i=0;s[i]!='\0';i++)
{
if((s[i]>='A')&&(s[i]<='Z'))
upper++;
else if((s[i]>='a')&&(s[i]<='z'))
lower++;
else if(s[i]==' ')
space++;
else if((s[i]>='0')&&(s[i]<='9'))
digit++;
else
other++;
}
cout<<upper <<'\t'<<lower<<'\t'<<space<<'\t'<<digit<<'\t' <<other;
return 0;
}

  • 写回答

3条回答

  • 小灸舞 2016-05-02 05:48
    关注

    输入的地方有问题,直接改成cin.getline(s, 20);就行,用cin>>s是不行的,因为你需要读入含空格的字符串,cin是做不到的

     #include<iostream>
    using namespace std;
    int main(int argc, char * argv[])
    {
        int upper=0,lower=0,digit=0,space=0,other=0,i=0;
        char s[20];
        cout<<"Input string:";
        cin.getline(s, 20);
        for(int i=0;s[i]!='\0';i++)
        { 
            if((s[i]>='A')&&(s[i]<='Z'))
                upper++;
            else if((s[i]>='a')&&(s[i]<='z'))
                lower++;
            else if(s[i]==' ')
                space++;
            else if((s[i]>='0')&&(s[i]<='9'))
                digit++;
            else
                other++;
        }
        cout<<upper <<'\t'<<lower<<'\t'<<space<<'\t'<<digit<<'\t' <<other;
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果