c++简单加密

C++ Simple Encryption

本文关键字:加密 简单 c++      更新时间:2023-10-16

我读了Bjarne Stroustrup写的《c++编程语言》这本书,他的一个练习是做一个简单的加密。我输入一些东西,用std::cin读取它并加密它+将加密的文本打印到屏幕上。我是这样做的:

In my int main():
std::string read;
std::cin >> read;
encript(read);

我的功能(只是一部分):

void encript(const std::string& r){
std::string new_r;
for(int i = 0; i <= r.length(); i++)
{
    switch(r[i])
    {
        case 'a':
            new_r += "a_";
            break;
        case 'b':
            new_r += "b_";
            break;
        case 'c':
            new_r += "c_";
            break;
        case 'd':
            new_r += "d_";
            break;
... //goes on this way 
    }
}
std::cout << new_r << std::endl;

我现在的问题是我真的要写每一个字符吗?我的意思是这些只是非大写字符。也有特殊字符,数字等。

还有别的方法吗?

当然还有另一种方法:

new_r += std::string(1,r[i]) + "_";

如果使用range-for,会更简洁:

std::string new_r;
for (char c : r) {
    new_r += c;
    new_r += '_';
}

这是相同的:

void encript(const std::string& r){
std::string new_r;
for(int i = 0; i < r.length(); i++) // change this too
{
    new_r += r[i];
    new_r += "_";
}
std::cout << new_r << std::endl;

或者您可以直接使用STL。不必使用c++ 11:

string sentence = "Something in the way she moves...";
istringstream iss(sentence);
ostringstream oss;
copy(istream_iterator<char>(iss),
     istream_iterator<char>(),
     ostream_iterator<char> (oss,"_"));
cout<<oss.str();
输出:

S_o_m_e_t_h_i_n_g_i_n_t_h_e_w_a_y_s_h_e_m_o_v_e_s_。_. _. _