我用C ++创建这个程序,要求用户输入带有大写和小写字母的电影标题。它确定并显示标题中大写和小写字母的数量。然后它创建3个字符串,将原始字符中的所有字符转换为大写,然后转换为小写,然后转换为相反的情况。它分别显示这些字符串。在显示大写和小写字母的数量后出现问题。程序输出一条错误消息,说明它必须请求Runtime以不寻常的方式终止它。我需要一些帮助来识别问题并修复它。谢谢 这是我的代码:
#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;
}
答案 0 :(得分:2)
您永远不会将upper
,lower
或swap
初始化为任何值。当您执行upper.at(i)
,lower.at(i)
或swap.at(i)
时,该计划将会中断。
您可以通过在第二次循环之前将upper
,lower
和swap
设置为title
来解决此问题。
变化:
...
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++)
...
输出:
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