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

时间:2018-05-15 06:17:34

标签: c++ arrays

我有一个"编码"文本基本上是通过将字符碰撞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 个答案:

答案 0 :(得分:0)

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

prompt[i] += INTEGRAL_VALUE;

在你的情况下,它会是这样的:

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

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