2015-10-05 33 views
0

如果輸入「'ABCD'',我希望輸出爲''ZABC''。 如果我輸入''hello world'',輸出必須是''gdkkn vnqkc''。如何將字符串中的字符轉換爲C++中的字母順序的前一個字符

我這樣做:

cout << "Enter text" << endl; 
cin >> input;` 

result_string = ConvertString(input); 

cout << endl << "The result is " << endl << result_string << endl; 

但我不知道如何定義ConvertString

謝謝你的幫助。 :)

+0

到目前爲止您嘗試過什麼?正如經常指出的那樣,SO不是一項免費編碼服務。 – owacoder

+0

這就是我所做的至今,因爲我不知道如何做到這一點,我不明白如何轉換字符串中的每個字符,而不使用一些複雜的東西......(我剛開始學習,所有我知道的是非常基礎)。 –

+0

我在Google和YouTube上到處尋找,並看到很多類似的東西,例如用數字轉換一系列字母或用另一個字母轉換輸入中的每個字母,但似乎沒有人問過這個。我只是要求一個小技巧,我不會要求某人爲我編程,我只是想了解C++ –

回答

1

你將不得不訪問字符串中的每個單獨的字符。字符串允許你隨機訪問內存,所以你可以用for循環來完成。

string input; 
cout << "Enter text" << endl; 
cin >> input; 

//traverse the string 
for (int i = 0;i < input.size(); i++) 
{ 
//check for A or a and move it to Z or z respectively 
if(input[i] == 65 || input[i] == 97) 
input[i] += 26; 
//change the value to minus one 
input[i]--; 
} 

cout << endl << "The result is " << endl << input << endl; 
return 0; 
+0

謝謝你的幫助和你的時間菲利普,它真的很友善。 –

1

有沒有聽說過凱撒密碼?

#include<iostream> 
#include<string> 
using std::endl; 
using std::cout; 
using std::cin; 


int main(){ 
    std::string input; 
    int count=0, length, n; 

    cout<<"enter your message to encrypt:\n"; 
    getline(cin,input); 
    cout<<"enter number of shifts in the alphabet:\n"; 
    cin>>n; 

    length=input.length();//check for phrase's length 

    for(count=0;count<length;count++){ 
     if(std::isalpha(input[count])){ 
      //lower case 
      input[count]=tolower(input[count]); 
      for(int i=0;i<n;i++){ 
       //if alphbet reaches the end, it starts from the beginning again 
       if(input[count]=='z') 
        input[count]='a'; 
       else 
        input[count]++;  
      }  
     }  
    } 

    cout<<"your encrypted message: \n"<<input<<endl; 

    return 0;  
} 
+0

謝謝楊帆! –

+0

非常值得一提的是* Caesar Cipher *術語,但是您正在「遞增」而不是「遞減」ASCII值,並且更改爲小寫可能會也可能不會被接受。 –

相關問題