简体   繁体   中英

Assign values to C# variables by reading characters from a text file

I have a task that requires setting the int variables in a C# method from a line in a text file, running through the program and then repeating but with variables from the second line of the text file.

Each line of the text file would look similar to this

3 5 10
2 7 15

I am new to C# and am learning fast but have hit a brick wall with this one. Any help of suggestions would be greatly appreciated.

Reading text from a file: https://msdn.microsoft.com/en-us/library/db5x7c0d(v=vs.110).aspx

Use Split() to turn "3 5 10", for example, into an array of strings like "3", "5", "10". Then use int.Parse() to change each item in the array into an int.

To read from the file, you can use the StreamReader class, or File.ReadAllLines() .

Then you can use String.Split(new[] {' '}) to get an array of strings (each one containing the number as a string) from the line.

Converting to an integer is easy, just foreach through and use the Convert class to change each to type int .

Keep in mind we're not here to write code for you, and there are quite a few answers to your question out there if you just break down what you're trying to do.

This can be done using a simple LINQ expression:

int[] numbers = File.ReadAllLines(path)
    .SelectMany(f => f.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
    .Select(f => Convert.ToInt32(f))
    .ToArray();

First, you read all lines into a string[] . Then you use SelectMany to split all lines into the numbers you have and at the end, you cast to int .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM