如何在 c++ 中递增数组值?

How can I increment array values in c++?

本文关键字:数组 c++      更新时间:2023-10-16

我有一个程序,基本上通过将字符撞1来"编码"文本。例如,abc变成了bcd。我正在尝试弄清楚如何让它使用 -5、8、12、6、1 而不是 1 的数组值。我被困在"提示符[i]++;"这会将字母增加 1。我将如何在此处使用数组值?

#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
string secret1;
cout << "Enter name of file to decode: "<< endl;
cin >> secret1;
fstream one;
one.open (secret1);
if(!one.good()) throw "I/O error";
string secret2 = "secret.txt";
ofstream fout;
fout.open("secret.txt"); //overwrite document

const int SIZE = 5; //array
int offset[SIZE] = {-5, 8, 12, 6, 1}; //array values
int counter = 0;
while (true)
{  
if (!one.good()) break;
one >> secret1;
string prompt = secret1;
int index = counter % SIZE;
for (int i = 0; i < prompt.length(); i++) // for each char in the 
string...
prompt[i]++; // bumps the ASCII code by 1
ofstream fout;
fout.open(secret2, ios::app);
fout << prompt << endl;
}
one.close();
fout.close();
}

要按任意值递增,请将++(始终递增 1(替换为+=。例如:

prompt[i] += INTEGRAL_VALUE;

在您的情况下,它将是这样的:

prompt[i] += offset[index];  // or [i % SIZE], depending on the desired semantics

这假定偏移量不会溢出prompt中的char值。如果可能发生溢出,则应将prompt [i]offset[index]都转换为unsigned char以确保模算术。