加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

程序在C中崩溃

发布时间:2020-12-16 10:33:28 所属栏目:百科 来源:网络整理
导读:我刚刚开始学习C,这是我正在为练习编写的一个程序: #include iostream#include stringusing namespace std;int main (){ int uppercase=0,lowercase=0,digits=0,other=0,i=0; int character; char* string; cout "Enter a string!n"; cin.getline(string,2
我刚刚开始学习C,这是我正在为练习编写的一个程序:

#include <iostream>
#include <string>
using namespace std;

int main ()
{
    int uppercase=0,lowercase=0,digits=0,other=0,i=0;
    int character;
    char* string;
    cout << "Enter a string!n";
    cin.getline(string,20); 

    while(true)
        {
        character = int(*(string+i));
        if (character==0)
            {
            break;
            }
        if (character > 64 && character < 91)
            {
            uppercase++;
            }
        if (character > 96 && character < 122)
            {
            lowercase++;
            }
        if (character > 47 && character <58)
            {
            digits++;
            }
        else
            {
            other++;
            }
        i++;
        }

    cout << "Upper case " << uppercase << "n";
    cout << "Lower case " << lowercase << "n";
    cout << "Digits " << digits << "n";
    cout << "Others " << other << "n";

    return 0;
}

程序完成打印结果后程序崩溃.我错过了一些非常明显的东西吗?

副问题:变量’other’总是增加,即使它不应该.我使用else语句错了吗?

解决方法

您还没有为字符串分配内存

试试这个(在堆栈上分配):

char string[256];

或(在堆上分配):

char* string = new char[256];

delete[] string;

UPDATE

使用std和预定义的isdigit(),isalpha()等,可以按如下方式重写代码:

#include <iostream>
#include <string>

int main ()
{
    int uppercase=0,other=0;

    std::cout << "Enter a string!n";

    std::string myline;
    std::getline(std::cin,myline);

    for (std::string::iterator i = myline.begin(); i != myline.end(); ++i)
    {
        if (isdigit(*i))
        {
            digits++;
        }
        else if (isalpha(*i))
        {
            isupper(*i) ? uppercase++
                        : lowercase++;
        }
        else
        {
            other++;
        }
    }

    std::cout << "Upper case " << uppercase << "n";
    std::cout << "Lower case " << lowercase << "n";
    std::cout << "Digits " << digits << "n";
    std::cout << "Others " << other << "n";

    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读