This program is using the ROT-13 algorithm successfully, but it is not capturing any special characters or numbers, instead, special characters and numbers are not being saved in the output file at all. What changes in my code do I need to make for numbers and special characters to output?
static void Encode ()
{
string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // declaring alphabet
string strROT13 = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"; // declaring alphabet using the ROT13 system
Console.WriteLine("Enter the name of the file you would like to encode (.txt, .bat, etc): "); // prompts user to read in file
string inputFile = Console.ReadLine();
if (!File.Exists(inputFile)) { // test to see if file is found
Console.WriteLine("File not found, please try again.");
return;
}
Console.WriteLine("Enter the name of the file you would like to save to (.txt, .bat, etc): "); // asks user where to save translated file
string outputFile = Console.ReadLine();
StreamReader input = new StreamReader(inputFile); // reads file
StreamWriter output = new StreamWriter(outputFile); // writes file
string str = ""; // reading file line by line
while ((str = input.ReadLine()) != null) // reads entire file
{
string encoded = "";
int length = str.Length;
if (length > 0)
{
foreach (char character in str) // takes each character from the line
{
if (character == ' ') // if a space in file, left unchanged
encoded += ' ';
else
for (int i = 0; i < 52; i++) // if character in array, then encoded
if (character == alphabet[i])
encoded += strROT13[i];
}
}
output.WriteLine(encoded); // writes encoded string to the new file
}
input.Close();
output.Close();
Console.WriteLine("The file was successfully encoded.");
}
One way to do this is to create a variable that we set to
trueif the character was found in thealphabetarray. Then, after the inner loop, we know that if the character wasn't found, it was a "special character" or a number, and we can just add it.For example: