这代码为啥就不正确

P1914 小书童——凯撒密码

kelon001 @ 2022-09-07 21:31:09

#include <iostream>
using namespace std;
int main()
{
    int n;
    cin>>n;
    n%=26;
    string a;
    cin>>a;
    for(int i=0;i<a.size();i++)
    {
        a[i]+=n;
        if(a[i]>'z')
        {
            a[i]=a[i]-'z'-1+'a';
        }
    }
    cout<<a;
}

我的代码为啥错了,查看输入输出正常啊 输入: 25 abcxyz 输出: zabwxy


by wangyuzhou @ 2022-09-07 21:42:07

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    int n;
    cin>>n;
    n%=26;
    string a;
    int o[51];
    cin>>a;
    for(int i=0;i<a.size();i++)
    {
        o[i]=int(a[i]);
        o[i]+=n;
        if(o[i]>int('z'))
        {
            o[i]=o[i]-'z'-1+'a';
        }
    }
    for(int i=0;i<a.size();i++)
    cout<<char(o[i]);
}

by wangyuzhou @ 2022-09-07 21:42:25

@kelon001


by wangyuzhou @ 2022-09-07 21:47:25

a[i]+=n可能超过ASCII范围,也就是大于127,无法比较

还有,#include <cstring>呢
a.size()要用

|