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

为何字符数组末尾多出'i'?C++非字母字符过滤问题求助

问题分析与解决:C++过滤字符时末尾多出意外字符

问题根源

你的问题出在循环范围错误和未初始化内存的干扰:

  1. 你用了char code[n];(n=10),这是编译器扩展的变长数组(非C++标准特性),数组中未被输入覆盖的位置会残留内存里的随机垃圾值。
  2. cin.getline(code, n)读取输入的"Ajith@#"后,仅填充了数组前7个位置,第8位是自动添加的'\0',但第9、10位还是随机值。
  3. 你循环时用了for(int i=0; i<n; i++),也就是会遍历整个10位数组。当i超过有效字符串长度后,那些随机垃圾值里刚好有一个字符'i'符合字母判定条件,被错误地加入到结果中,导致输出多了一个i。

解决方案

方案1:用std::string(推荐,更安全规范)

直接用string处理,彻底避开数组越界和未初始化内存问题:

#include<iostream>
#include<string>
using namespace std;

int main() {
    int n;
    cin >> n;
    cin.ignore();
    string code;
    getline(cin, code);

    string result;
    for(char c : code) {
        if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
            result += c;
        }
    }
    cout << result << endl;
    return 0;
}

方案2:修复原数组代码

如果坚持用字符数组,只需把循环范围改为字符串实际长度,而非n:

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

int main() {
    int n;
    cin >> n;
    char code[n];
    cin.ignore();
    cin.getline(code, n);

    int j = 0;
    // 只遍历输入的有效字符部分,避免碰随机内存值
    int len = strlen(code);
    for(int i = 0; i < len; i++) {
        if((code[i] >= 'A' && code[i] <= 'Z') || (code[i] >= 'a' && code[i] <= 'z')) {
            code[j] = code[i];
            j++;
        }
    }
    code[j] = '\0';
    cout << code;
    return 0;
}

额外提醒:char code[n]不是C++标准支持的写法,建议尽量用std::string或std::vector<char>替代,减少潜在风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:15:42