I am just starting to learn C++ and this is a program I'm writing for an exercise:
#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;
}
The program crashes after it finishes printing the results. Am I missing something really obvious here?
Side question: The variable 'other' is always increased even if it shouldn't be. Am I using the else statement wrong?
You have not allocated memory for string
Try this (allocate on stack):
char string[256];
or (allocate on heap):
char* string = new char[256];
delete[] string;
UPDATE
Using std and predefined isdigit(), isalpha(), etc, the code can be rewritten as follows:
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With