Unknown runtime error

U stands for uppercase letters, l stands for lowercase letters,n stands for numbers and c is the total letter of characters. I am trying to get it to count how many uppercase letters, lower case letters, numbers and characters are in the string s1 and if the user inputs a # I want it to end even if there are letters afterward. It compiles fine, but when I go to run it it comes up with an error that just says and Unknown run time error has occurred. Thanks for the help!

Here is my program:
#include <string>
#include <iostream>
#include<cctype>

using namespace std ;

int main()
{
int u, l, n, c;
u=0;
l=0;
n=0;
c=0;
string s1;
cout << "Enter a sentence";
getline(cin,s1);
while (c<=s1.length())
{
if (isupper(s1.at(c)))
u++;
if (islower(s1.at(c)))
l++;
if (isdigit(s1.at(c)))
n++;
c++;
if (s1.at(c)=='#')
break;
}
cout<<u<<l<<n<<c<<endl;
return 0;
}

Last edited on
First of all, you increment c before you check if the current character is '#'. This means that you skip over the '#' if it is the first character.

More importantly, your while condition is wrong. You should be doing the loop like this:

while (c < s1.length())

Notice that it should be strictly less than, not less than or equal to. As it stands, in the final iteration,
c == s1.length(), so s1.at(c) would be the string termination character, '\0'. This isn't a big deal. This just means that it is not upper case, lower case, or a digit. The problem happens next when c is incremented and this line if (s1.at(c)=='#') goes past the end of the string.
Thanks for the help! I got it to work, with your suggestions! Here is the working code if you are interested:

#include <string>
#include <iostream>
#include<cctype>

using namespace std ;

int main()
{
int u, l, o, c, s1l;
u=0;
l=0;
o=0;
c=0;
string s1;
cout << "Enter a sentence ";
getline(cin,s1);
s1l=s1.length();
while (c < s1l)
{
if (isupper(s1.at(c)))
u++;
if (islower(s1.at(c)))
l++;
if (isdigit(s1.at(c)))
o++;
if (s1.at(c)=='#')
break;
c++;
}
cout<<" There are "<<u<<" uppercase letters.\n There are "<<l<<" lower case letters.\n There are "<<o<<" numbers.\n There are "<<c<<" characters."<<endl;
return 0;
}
Good to hear! Remember to mark the topic as solved.
Last edited on
Topic archived. No new replies allowed.