需要帮助编码c++字符串增加ASCII值

Need help encoding C++ strings by increasing ASCII value

本文关键字:增加 ASCII 字符串 c++ 帮助 编码      更新时间:2023-10-16

我到处寻找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类型,防止溢出错误。