gpt4 book ai didi

c++ - 程序在 C++ 中崩溃

转载 作者:太空狗 更新时间:2023-10-29 19:44:01 24 4
gpt4 key购买 nike

我刚开始学习 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 语句?

最佳答案

你还没有为string分配内存

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

char string[256];

或(在堆上分配):

char* string = new char[256];

delete[] string;

更新

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

#include <iostream>
#include <string>

int main ()
{
int uppercase=0, lowercase=0, digits=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;
}

关于c++ - 程序在 C++ 中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16523417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com