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

为何我的C++代码末尾输出随机垃圾值?Codeforces解题求助

输出末尾出现垃圾值的原因及修复方案

问题根源

你使用的是C风格字符数组,cout输出这类数组时,会从起始地址开始读取字节,直到碰到**空字符'\0'**才停止。但你的代码只给数组前n个位置赋值,没有在末尾添加'\0',导致输出时越界读取数组后面的内存内容,也就是你看到的垃圾值。

修复方案

方案一:手动添加字符串结束符

给数组多分配一个字节的空间存放'\0',循环结束后手动添加结束标记:

#include <iostream>
#include <string>
#include <conio.h>
#include <set>
#include <vector>
using namespace std;

int main(){
    int n, k;
    cin >> n >> k;
    char password[n+1]; // 多留一个位置存结束符
    for(int i=0; i<n; i++){
        password[i]= 'a' +  i%k;
    }
    password[n] = '\0'; // 添加字符串结束标记
    cout << password;
}

方案二:改用C++ string类型(更推荐)

string会自动管理内存和结束符,代码更简洁安全,完全符合C++标准:

#include <iostream>
#include <string>
#include <conio.h>
#include <set>
#include <vector>
using namespace std;

int main(){
    int n, k;
    cin >> n >> k;
    string password;
    password.reserve(n); // 预分配内存,避免多次扩容提升效率
    for(int i=0; i<n; i++){
        password += 'a' + i%k;
    }
    cout << password;
}

额外提示

注意:char password[n]是C99的变长数组特性,C++标准并未定义该语法。虽然多数编译器支持,但在Codeforces这类平台可能存在兼容性问题,改用string或动态分配内存(如new char[n+1])会更稳妥。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:13:15