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

基于CPF第9位索引数组遇0无输出问题排查求助

问题解决:CPF第9位为0时无法输出对应州名

问题原因

你的代码中char cpf[11]数组长度不足。当输入11位CPF数字时,C语言字符串需要额外1字节存储终止符\0,数组越界会触发未定义行为,可能导致state[0]的内容被破坏,或者cpf[8]的取值异常,从而出现第9位为0时无输出的情况。

修复后的代码

#include <stdio.h>
#include <string.h>

int main(void){
    char state[10][100] = {"Rio Grande do Sul", "Distrito Federal, Goias, Mato Grosso, Mato Grosso do Sul ou Tocantins", "Amazonas, Para, Roraima, Amapa, Acre ou Rondonia", "Ceara, Maranhao e Piaui", "Paraiba, Pernambuco, Alagoas ou Rio Grande do Norte", "Bahia ou Sergipe", "Minas Gerais", "Rio de Janeiro ou Espirito Santo", "Sao Paulo", "Parana ou Santa Catarina"};
    
    // 改为12位,容纳11个数字+1个字符串终止符
    char cpf[12];
    printf("Enter a CPF: ");
    scanf("%s", cpf);
    int digit = (int)(cpf[8]) - 48; 

    printf("STATE: %s\n", state[digit]);
    return 0;
}

额外优化建议

  • 增加输入长度限制,彻底避免数组越界:将scanf("%s", cpf)改为scanf("%11s", cpf),限制最多读取11个字符。
  • 添加输入合法性检查,确保CPF为11位数字,避免因输入非数字字符导致digit计算错误。

验证结果

输入00000000000时,输出将正常显示:

STATE: Rio Grande do Sul

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:31:01