如何在C++中使用指定数组值对字符串字符进行偏移编码?
解决你的ASCII编码偏移问题
看起来你已经把核心思路理清楚了——用循环数组替代固定的+1偏移,只是卡在了关键的字符修改步骤上。咱们一步步来修正:
核心修改点
原来的prompt[i]++;是固定给每个字符的ASCII加1,现在需要替换成加上数组中循环取出的偏移值。同时还要注意让计数器递增,这样才能循环遍历数组里的元素。
具体修改步骤
替换固定偏移为数组值
把prompt[i]++;改成:prompt[i] += offset[index];这样就会用数组
offset中当前索引对应的数值来修改字符的ASCII值。递增计数器实现数组循环
你的代码里已经计算了index = counter % SIZE,但counter从未递增,导致每次都用数组的第一个元素。所以在处理完一个单词后,要加上counter++;。优化文件打开逻辑
原来的代码每次循环都重新创建ofstream并打开文件,这既低效又容易出问题。建议把ofstream fout;的定义和打开操作移到循环外面,只打开一次。
修改后的完整代码
#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"; const string secret2 = "secret.txt"; ofstream fout(secret2, ios::app); // 只打开一次文件,追加模式 if (!fout.good()) throw "Failed to open output file"; const int SIZE = 5; int offset[SIZE] = {-5, 8, 12, 6, 1}; int counter = 0; while (one >> secret1) { // 简化循环条件,直接读取单词直到文件结束 string prompt = secret1; int index = counter % SIZE; for (int i = 0; i < prompt.length(); i++) { prompt[i] += offset[index]; // 使用数组中的偏移值 } fout << prompt << endl; counter++; // 递增计数器,下次用数组的下一个元素 } one.close(); fout.close(); return 0; }
额外说明
- 我把循环条件改成了
while (one >> secret1),这样更简洁,不需要手动判断one.good()。 - 注意字符的ASCII值可能会因为偏移超出可打印字符范围,如果需要处理这种情况,可以额外加判断(比如限制在
0x20到0x7E之间)。
内容的提问来源于stack exchange,提问作者Paulo Manalo
相关产品推荐
相关产品推荐

