2013-04-06 66 views
2

我讀過Bjarne Stroustrup編寫的「C++編程語言」一書,他的一個練習是做一個簡單的加密。我輸入東西,用std :: cin讀取並加密它並將加密的文本打印到屏幕上。這是我做的:C++簡單加密

在我INT主要()

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; 

我現在的問題我真的有寫每一個字符?我的意思是這些只是非大寫字母。還有特殊字符,數字等。

有沒有其他的方法呢?

+2

如果C++ 11正常,'new_r + = {r [i],'_'};'。這需要一個由字符和下劃線組成的初始化程序列表(想想數組初始化),並將其添加到字符串的末尾。 – chris 2013-04-06 20:46:51

+0

你可以得到a的個數並計算其他人 – Bakudan 2013-04-06 20:48:03

+0

@Bakudan,除非它們不保證是連續的。 – chris 2013-04-06 20:48:28

回答

3

這將是相同的:

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_。 _。 _。 _

+0

'+ ='可以採用單個字符,與構造函數不同,所以'new_r + = r [i];'起作用。 – chris 2013-04-06 20:52:31

4

有ofcourse另一種方式:

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

如果使用範圍,對,它的清潔:

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