Reputation: 39
I'm creating this program in C++ that requests the user enter a movie title with upper and lowercase letters. It determines and displays the number of upper and lowercase letters in the title. It then creates 3 strings that converts all of the characters in the original to uppercase, then to lowercase, then to the opposite case. It displays these strings separately. The issue arises after it displays the amount of upper and lowercase letters. The program outputs an error message saying that it must request Runtime to terminate it in an unusual way. I need some help identifying the problem and fixing it. Thanks Here is my code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
string title, upper, lower, swap;
int upCount = 0, lowCount = 0;
cout << "Please enter your favorite movie title:\n(it should have upper and lowercase letters)" << endl;
getline(cin, title);
for (int i = 0; i < title.size(); i++)
{
if (isupper(title.at(i)))
upCount++;
else if (isalpha(title.at(i)))
lowCount++;
}
cout << title << " has " << upCount << " uppercase letters and " << lowCount << " lowercase letters." << endl;
for (int i = 0; i < title.size(); i++)
{
upper.at(i) = title.at(i);
lower.at(i) = title.at(i);
swap.at(i) = title.at(i);
}
for (int i = 0; i < title.size(); i++)
{
if (isupper(title.at(i)))
swap.at(i) = tolower(int(swap.at(i)));
else
swap.at(i) = toupper(int(swap.at(i)));
upper.at(i) = toupper(int(upper.at(i)));
lower.at(i) = tolower(int(lower.at(i)));
}
cout << upper << endl
<< lower << endl
<< swap << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Upvotes: 1
Views: 1812
Reputation: 9690
You never initialize upper
, lower
, or swap
to any value. When you do upper.at(i)
, lower.at(i)
, or swap.at(i)
the program will break.
You can fix this by setting upper
, lower
, and swap
all equal to title
before that second loop.
Change:
...
cout << title << " has " << upCount << " uppercase letters and " << lowCount << " lowercase letters." << endl;
upper = lower = swap = title; //Add this
for (int i = 0; i < title.size(); i++)
...
Output:
Please enter your favorite movie title:
(it should have upper and lowercase letters)
V for Vendetta
V for Vendetta has 2 uppercase letters and 10 lowercase letters.
V FOR VENDETTA
v for vendetta
v FOR vENDETTA
Upvotes: 2