You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决C++数组编程中的‘stack corrupted’(栈损坏)运行时错误

问题描述

以下是我的代码:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    cout << "please input a string: ";
    char str[50];
    cin >> str[50];
    int i;
    for (i = 0; i <= 49; i++)
    {
        cout << str[i] << " ";
    }

}

无论输入多少字符,程序都会报错:Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted.

我试图在Visual Studio中编写代码,将用户输入的字符串存入char数组,拆分每个字符后统计其中字符、数字和标点符号的数量,现需解决该栈损坏问题。

问题原因与解决方法
  • 核心错误:cin >> str[50]; 是错误写法。str数组的下标范围是0到49,str[50]属于越界访问,直接给这个位置赋值会破坏栈内存,触发栈损坏报错。正确写法是cin >> str;,cin会自动将输入字符串存入数组起始位置,并添加字符串结束符\0。
  • 避免乱码输出:原循环遍历数组全部50个元素,若输入字符串长度不足50,未初始化的元素会输出乱码。应修改为遍历到字符串结束符\0:
    for (i = 0; str[i] != '\0'; i++)
    {
        cout << str[i] << " ";
    }
    
  • 带统计功能的完整修正代码:
    #include<iostream>
    #include<string>
    #include<cctype> // 用于字符判断函数
    using namespace std;
    int main()
    {
        cout << "please input a string: ";
        char str[50];
        cin >> str; // 修正输入方式
        // 若要读取含空格的整行输入,替换为:cin.getline(str, 50);
    
        int i;
        // 输出拆分后的每个字符
        cout << "拆分后的字符:";
        for (i = 0; str[i] != '\0'; i++)
        {
            cout << str[i] << " ";
        }
        cout << endl;
    
        // 统计字符、数字、标点数量
        int charCount = 0, digitCount = 0, punctCount = 0;
        for (i = 0; str[i] != '\0'; i++)
        {
            if (isalpha(static_cast<unsigned char>(str[i]))) {
                charCount++;
            } else if (isdigit(static_cast<unsigned char>(str[i]))) {
                digitCount++;
            } else if (ispunct(static_cast<unsigned char>(str[i]))) {
                punctCount++;
            }
        }
    
        cout << "字符数量:" << charCount << endl;
        cout << "数字数量:" << digitCount << endl;
        cout << "标点数量:" << punctCount << endl;
    
        return 0;
    }
    
  • 补充说明:使用cin >> str只能读取不含空格的字符串,若需要读取包含空格的整行输入,改用cin.getline(str, 50);,该函数会读取直到换行符的所有字符,且最多读取49个字符(预留一个位置存储字符串结束符\0)。

内容的提问来源于stack exchange,提问作者Throwa0112

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 06:35:24