绝对值未在 ascii 中正确添加

Absolute value not getting added correctly in ascii

我用C++写了一个凯撒密码的小程序。 我认为我在逻辑上做得很好。但是,由于某些我无法理解的奇怪原因,ASCII 添加出错了。这是我的代码: 此行有问题: "s[i] = (abs(s[i])) + k;"

我的输入如下:

2

xy

87

输出应该是: gh

我得到的输出为:ed.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int n;
    cin >> n;
    string s;
    cin >> s;
    int k;
    cin >> k;
    k = k % 26;
    for(int i = 0; i<s.size(); i++){
        if((abs(s[i]) >=65 && abs(s[i]) <=90) || (abs(s[i]) >= 97 && abs(s[i]) <= 122)){
            cout << "k is: "<<k << endl; //k should be 9
            //for x abs(s[i]) should be 120
            cout << "Absolute value is: "<<abs(s[i]) <<endl;

            s[i] = (abs(s[i])) + k; // thish is not 129.. i am getting 127
            cout << "After adding K: "<<abs(s[i]) << endl; 
            if((abs(s[i]) > 90) && (abs(s[i]) < 97))
                s[i] = abs(s[i]) - 26;
            if(abs(s[i]) > 122){
                s[i] = abs(s[i]) - 26;
            }                            
        }
    }
    for(int i =0 ; i< s.size(); i++)
        cout<<s[i];
    return 0;
}

如有任何帮助,我们将不胜感激。谢谢。

这一行:

s[i] = (abs(s[i])) + k;

计算出一个大于 127 的值。字符串在内部使用 char 类型,因此您在 s[i] 中放置了一个超出范围的值:实现定义:模、截断...

之后减去 26 没有帮助:数据已经被销毁。

修复:一路用整数工作,最后赋值回s[i]

for(int i = 0; i<s.size(); i++){
    int v = s[i];
    if((abs(v) >=65 && abs(v) <=90) || (abs(v) >= 97 && abs(v) <= 122)){
        cout << "k is: "<<k << endl; //k should be 9
        //for x abs(v) should be 120
        cout << "Absolute value is: "<<abs(v) <<endl;

        v = (abs(v)) + k; // integer won't overflow
        cout << "After adding K: "<<abs(v) << endl; 
        if((abs(v) > 90) && (abs(v) < 97))
            s[i] = abs(v) - 26;
        if(abs(v) > 122){
            s[i] = abs(v) - 26;
        }                            
    }
}

我已经测试过了,我 gh 没问题(而且速度更快,因为对 s[i] 的数组访问较少)