-3

I want to build a program to save text to files , but I want my program to secure or encrypt the content of the text , for example , if the user input "salamence" to the program , the program would output (into a file) "hjkjupfqp" or something like that so people can't read it unless they have access to the program (I want the program to be able to decrypt the text file too) so it is possible in c++ to read strings input one by one character and modify them into another characters , and how to do that ?

Mark Gardner
  • 442
  • 1
  • 6
  • 18
salmanrf
  • 15
  • 1
  • 6

1 Answers1

-1

A string is a sequence of chars put in a container that has other stuff in it. The chars themselves can be accessed through the [] operator. A char is basically an 8-bit integer that can be displayed. An integer can be manipulated arithmetically(+,-,*,...), bit-wise(&,^,|,<<,...), etc.

So you could do something like this:

#include <iostream>
#include <string>
using namespace std; //bad idea, but simplifies stuff
int main(){
    string s;
    cin>>s; //reads the string
    for(int i=0;i < s.size;i++){ //loops through all characters of the string
        s[i]++; //adds one to the string
    }
    cout<<s; //outputs the modified string
}

This will turn "abc" into "bcd", wich is a rather stupid form of encryption, but it proves the concept.

To decrypt you would need to copy the loop, but replace s[i]++ with s[i]--.

Since you seem to be a beginner, I would actually recommend using c-style strings, but that is outside the scope of this question.

Mark Gardner
  • 442
  • 1
  • 6
  • 18
  • yes i am a complete beginner thanks for your reply , but why "using namespace std;" is a bad idea ? – salmanrf Dec 19 '17 at 08:32
  • [a quick search brings this up](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Mark Gardner Dec 21 '17 at 09:44