Question:
C++ help encrypting a file?
2010-02-23 11:55:02 UTC
i have the following function which works, its encrypts a text file, well its suppose to shift the letters of a text file by whatever the user wants, lets say the text file says "zoo" if the user wants to shift the letters by 1 to the right the output of it should say "app"
but lets say i want to shift it 13 to the right, it wont give the correct results
instead of giving me "mbb" it gives me something random it outputs "\207bb"
anyone wants to help me fix it??
p.s i have to keep it as a vector


void rotateEncrypt(vector V1, vector V2, int rotKey)
{
char ch;
int k;
string word = V1[0];
for (unsigned i=0; i{
if(word[i]!=' '){
ch = tolower( word[i]);
ch = ch + rotKey;
if(ch > 'z')ch = 'a' + (ch - 'z' -1);
word[i] = ch;
}
}
V2.push_back(word);
ofstream fo("simpler.txt" ,ios::app);
fo<< word <<'\n';
fo.clear();
fo.close();
}
Three answers:
The Phlebob
2010-02-23 21:26:48 UTC
Seems like the problem lies in this statement:



if(ch > 'z')ch = 'a' + (ch - 'z' -1);



By the time the program makes this test, ch has already been rotated past the end of the alphabet range of the ASCII character set.



Hope that helps.
peteams
2010-02-23 13:04:48 UTC
Your problem is you declared ch as char rather than int.



Why so? In your compiler char is really a tiny integer which can represent values in the range -128..127. When you add 13 to 122 (the code for 'z') you don't get 135 because that's too big, you get -19. So when you ask "is -17 greater than 122" the computer says no.



Make ch an int and it should fix your problem. When you assign word[i] = ch you might get a complaint from the compiler, which you'd fix using word[i] = (char)ch, or better word[i]=static_cast(ch)
Suspicious Intent
2010-02-23 13:00:14 UTC
Everything is correct except that you are forgetting that there are more than 26 ASCII characters defined in this programming language so when you shift by 13 you are shifting into numeric values and other ASCII characters.



For a full list of ASCII Characters and their equivalent integer values check out:



http://web.cs.mun.ca/~michael/c/ascii-table.html



I'm not sure how C++ handles this but in c you could do something like:



int myInt = 'a'

printf(%d\n", myInt);



which would print out the equivalent numerical value of 'a' which is 97.



The integer values of letter text range from 65-122 which covers A-Za-z



Hope this helps.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...