c++ - C++字符串程序引起的运行时错误

标签 c++ string runtime dev-c++

我正在用 C++ 创建这个程序,它要求用户输入带有大小写字母的电影片名。它确定并显示标题中大小写字母的数量。然后它创建 3 个字符串,将原始字符中的所有字符转换为大写,然后转换为小写,最后转换为相反的大小写。它分别显示这些字符串。问题出现在它显示大小写字母的数量之后。该程序输出一条错误消息,指出它必须请求运行时以一种不寻常的方式终止它。我需要一些帮助来确定问题并解决问题。谢谢 这是我的代码:

#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;
}

最佳答案

您永远不会将 upperlowerswap 初始化为任何值。当您执行 upper.at(i)lower.at(i)swap.at(i) 时,程序将中断。

您可以通过在该秒之前将 upperlowerswap 都设置为 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

关于c++ - C++字符串程序引起的运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35121952/

相关文章:

C++四舍五入到1位小数,显示2位小数

java - 当给定起始日期时,如何在 Java 中动态创建日期字段?

c++ - 从大写字母转换为小写字母,反之亦然

java - 在运行时更改类的所有实例的方法

ios - 如何在 Swift 中用不同的 block 实现 objc_setAssociatedObject?

c++ - 从 WinRT C++ 组件访问 COM 对象

c++ - 为我的球员名单选择最佳结构

java - 在哪里放置外部文件来配置 Eclipse 中的运行?

c++ - delete[] 和内存泄漏

python - 如何检查一个字符串是否包含 python 中字母表的所有字母?