Mohan Nassif
Mohan Nassif

Reputation: 1

How to convert characters in a string to a previous character in alphabetical order in C++

If I input ''ABCD'' I want the output to be ''ZABC''. If I input ''hello world'' the output has to be ''gdkkn vnqkc''.

I did this:

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

result_string = ConvertString(input);

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

But I don't know how to define ConvertString.

Thank you for the help. :)

Upvotes: 0

Views: 209

Answers (2)

夢のの夢
夢のの夢

Reputation: 5846

ever heard of caesar cipher?

#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;    
}

Upvotes: 1

Felipe Centeno
Felipe Centeno

Reputation: 3747

You would have to access every individual char in the string. String allows you to access memory randomly, so you can do so with a for loop.

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;

Upvotes: 1

Related Questions