需要帮助编码c++字符串增加ASCII值
Need help encoding C++ strings by increasing ASCII value
我到处寻找c++代码,从用户那里获取消息,并通过增加每个字符的ASCII值对其进行编码(显然不是很安全,但足够简单)。我已经设法把一个程序,返回几个值更高的字符,但不能弄清楚如何做一个完整的消息,包括空格。我打算做一个解码器,做相反的之后。任何帮助都会非常感激。提前谢谢。
单值c++程序-
#include <iostream>
using namespace std;
int main(){
char ascii;
cout << "Enter a character: ";
cin >> ascii;
cout << "Its ascii value is: " << (int) ascii << endl;
return 0;
}
工作编码器示例在VBS -
set x = WScript.CreateObject("WScript.Shell")
entxtde = inputbox("Enter text to be encoded")
entxtde = StrReverse(entxtde)
x.Run "%windir%notepad"
wscript.sleep 1000
x.sendkeys encode(entxtde)
function encode(s)
For i = 1 To Len(s)
newtxt = Mid(s, i, 1)
newtxt = Chr(Asc(newtxt)+3)
coded = coded & newtxt
Next
encode = coded
End Function
std::string originalString = "";
std::string newString = "";
int incrementValue = 1;
std::cout << "Input a string to encode: ";
std::cin >> originalString;
for(int i = 0; i < originalString.length(); i++) {
newString += (originalString.at(i) + incrementValue);
}
std::cout >> "New string is " + newString
只要改变incrementValue
来改变它的编码方式。如果incrementValue = 1, "Hello" = "Ifmmp"
要反转它,只需将其更改为减去incrementValue
而不是添加相同类型的for
循环。我觉得很简单
这可以在一行中完成,如果您希望保持在80列以下,也可以在两行中完成。其中value
是您希望加密的字符串,offset
是偏移值:
auto caesar = [offset](CharT c){return c + offset;};
std::transform(value.begin(), value.end(), value.begin(), caesar);
对于额外的点,你可以使它工作与任何类型的字符串通过模板的字符类型:
template <typename CharT>
std::basic_string<CharT> caesarEncode(std::basic_string<CharT> value, CharT offset){
auto caesar = [offset](CharT c){return c + offset;};
std::transform(value.begin(), value.end(), value.begin(), caesar);
return value;
}
由于看起来您可能在实际获取带有空格的字符串时遇到困难,因此您可以使用标准库的getline
函数获得一个,该函数默认情况下获取源流的一整行。
// narrow (CharT = char)
std::string value;
std::getline(std::cin, value);
// wide (CharT = wchar_t)
std::wstring wvalue;
std::getline(std::wcin, wvalue);
的实际编码将按如下方式完成:
char offset = 12;
auto encoded = caesarEncode(value, offset);
wchar_t woffset = 12;
auto wencoded = caesarEncode(wvalue, woffset);
你可以在coliru上看到一个实际的例子
真的很简单。首先,将输入作为字符串。然后,迭代每个字符,添加你想要的。为了确保该值保持有效且易于反转,您可以根据char的最大值对该值进行建模,即255。
int main () {
std::string input; // to store the text
std::getline(std::cin, input); // get the text
const int _add = 12; // value added
const int max_size = 255; // max value of a char
for (int i = 0; i < input.size(); ++i)
input[i] = (input[i] + _add) % max_size;
/* now the input is properly modified */
}
注意: _add
是int类型,防止溢出错误。
相关文章:
- 数组索引的值没有增加
- 为什么我的代码在输出中增加了93天
- 有效地使用std::unordered_map来插入或增加键的值
- C++ 动态数组每次添加时将大小增加 1 - 错误
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 为什么要增加导致崩溃的指针
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 有没有办法通过使用十进制 ASCII 代码自动类型扣除来获取字符?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- ascii 和 unicode 在处理级别有什么区别吗?
- 在C++中使用 ASCII 代码将输入从小写转换为大写
- 弄清楚如何在C++中将整数读入 ASCII
- 如何修复艺术ASCII,我点击一个字母就可以了,但输入一个阶段艺术出来了
- 使用指针将 ASCII 值添加到整数
- 用于 ASCII 的环绕式 C++
- 增加传递地址的值
- RE2 不匹配非 ASCII 字符
- 用于增加 ASCII 值的循环
- 我如何从ASCII转换到十六进制值,也增加char指针
- 需要帮助编码c++字符串增加ASCII值