如何在 c++ 中递增数组值?
How can I increment array values in c++?
我有一个程序,基本上通过将字符撞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
以确保模算术。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '