The objectives of this assignment are to 1) learn basic IO using the console 2) learn to read from a file.
static void Main(string[] args) { // get name of file to process Console.Write("Enter name of file containing integers : "); String fileName = Console.ReadLine(); // does the file exists? if (!System.IO.File.Exists(fileName)) { Console.WriteLine("Unable to open file"); Console.ReadLine(); return; } // convert each string into an integer and store in "eachInt[]" string fileContents = System.IO.File.ReadAllText(fileName); string[] eachString = fileContents.Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); int[] eachInt = new int[eachString.Length]; for (int i = 0; i < eachString.Length; i++) eachInt[i] = int.Parse(eachString[i]); // sort the numbers // print the array eachInt[] // exit the program Console.WriteLine("-------------------"); Console.Write("pressing Enter Key to exit..."); Console.ReadLine(); }This code should not contain any errors. It should compile and run.
Try running this code. It should pause and ask you for a file name. Just give it a silly name like "bob" and the program should tell you the file does not exist.
The if statement checks to see if the file exists. If the file does not exist, an error is printed to the console. The return statement causes main to exit and kill the program.
The next few lines are tricky. Just like Java, C# does not like to read numbers. C# likes to read strings. But we can convert strings into integers.
The first line in that block reads all the text from the file into a single huge string named "fileContents". The next statement uses the Split function to break fileContents into a bunch of little strings. We tell Split that the little strings are separated in the file by spaces, tabs, returns, and new lines. The Parse function is then used to convert each little string in eachString into an array of integers named "eachInt".
So now, eachInt is an array where each element of the array is an integer from the file.
Here is my text file:
12 4 88 3 19 47 99 0After you create your text file, try running the application again and give it the name of your file. The application should not give an error message. But, it will not do anything with the numbers until you add that code.
I suggest writing the printing loop first. Then write the code to sort the array. Use the sort function that is built into C#. To figure out how to use the sort function, Google it.