Friday, July 31, 2009

Need more help with c++ program?

ok i wrote an encryption program that reads in letters and prints out numbers and it works, but it doesnt work right


heres what i have:





int option;


cout%26lt;%26lt;"Enter 1 to encrypt, 2 to decrypt, 3 to quit"%26lt;%26lt;endl;


cin%26gt;%26gt;option;


while (option!=3){


if (option==1) cout%26lt;%26lt;"Enter a message to encrypt (! to quit)"%26lt;%26lt;endl;


char letter;


cin%26gt;%26gt;letter;


while (letter!='!'){


if (letter='k') cout%26lt;%26lt;"1 ";


then 26 more ifs for each other letter


cin%26gt;%26gt;letter;


}


}


for some reason it keeps printing out all of the numbers for each letter i enter


im not sure how to do it right

Need more help with c++ program?
you are doing an assignment in your if instead of a comparison.





if (letter='k') cout%26lt;%26lt;"1 ";





Should be





if (letter=='k') cout%26lt;%26lt;"1 ";
Reply:From your program:





if (letter='k') cout%26lt;%26lt;"1 ";





You need:





if (letter=='k') cout%26lt;%26lt;"1 ";





One '=' sets letter to 'k'





There's a better way of doing this.... Since you're converting a-z to 1-26 you can subtract 'a' from each character:





letter -= 'a' + 1;





Of course, if it's a capital letter you want to do:





letter -= 'A' + 1;
Reply:I used to have a similar problem until I started using switch case structures.


So, instead of all the if statements use a switch case structure with a number for each letter.


Note: In the first cout%26lt;%26lt; it is wise to notify the user that using ! will end the encryption loop.


No comments:

Post a Comment