How do I make this an int array, instead of a string array? I got this as a challenge since I am a beginner programmer.
static void Main(string[] args)
{
string [] lines = System.IO.File.ReadAllLines(@"input.txt"); // <- make this an int array instead.
// Display the file contents by using a foreach loop.
System.Console.WriteLine("Contents of input.txt = ");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine("\t" line);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
// Wait before closing
Console.ReadKey();
}
CodePudding user response:
I think you are looking for int.Parse(string). It will try to convert a string to an int, throwing an error if it can’t be done. There’s another version called TryParse() that returns a book to check if successful or not to do your own error handling.
You just loop through your lines array and copy the parsed ints into an int array.
CodePudding user response:
You can use Select
to map values of a collection.
int[] = File.ReadAllLines("c:/myFile.txt")
.Select(x => int.Parse(x))
.ToArray()
Here is a shorter "point-free" style syntax:
int[] = File.ReadAllLines("c:/myFile.txt")
.Select(int.Parse)
.ToArray()