Reputation: 31
I have a text file that displays students names and their scores. The format looks like this:
James Johnson, 85
Robert Jones, 90
Lindsey Parks, 98
etc.
I have 10 names and scores all in the above format. My problem is how do I split the text file by the delimiter, and use the integers from the text file
Here is my code so far:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.FileIO;
namespace TextFiles1
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(@"C:\Users\jonda\Desktop\StudentScores.txt.txt");
string data = sr.ReadLine();
while (data != null)
{
Console.WriteLine(data);
string[] names = data.Split(',');
data = sr.ReadLine();
}
int total = 0;
double average = 0;
for (int index = 0; index < data.Length; index++)
{
total = total + data[index];
}
average = (double)total / data.Length;
Console.WriteLine("Average = " + average.ToString("N2"));
int high = data[0];
for (int index = 0; index < data.Length; index++)
{
if (data[index] > high)
{
high = data[index];
}
}
Console.WriteLine("Highest Score =" + high);
sr.Close();
Console.ReadLine();
}
}
}
Upvotes: 2
Views: 67
Reputation: 10393
First of all, it's a good idea to separate file operations and other operations. File operations are slow and costly, and should be completed as soon as possible. I would use a separate method, read the lines into a List and close the file operation first.
private static List<string> ReadFile(string path)
{
List<string> records = new List<string>();
using (StreamReader sr = new StreamReader(path))
{
while (!sr.EndOfStream)
records.Add(sr.ReadLine());
}
return records;
}
Then I would pass that list to another function and calculate average, max etc.
private static void CalculateAverage(List<string> lines)
{
char[] seperator = new char[] { ',' };
List<int> scores = new List<int>();
if (lines != null && lines.Count > 0)
{
foreach (string line in lines)
{
Console.WriteLine(line);
string[] parts = line.Split(seperator);
int val;
if (int.TryParse(parts[1], out val))
scores.Add(val);
}
}
Console.WriteLine("Average: {0}", scores.Average());
Console.WriteLine("Highest Score: {0}", scores.Max());
}
Then in your main program call the methods like this:
List<string> lines = ReadFile(path);
CalculateAverage(lines);
Upvotes: 3
Reputation: 3735
Use Regex to find each person info and then split each of them and extract Name
and Score
.
Try like this:
var inputStr = "James Johnson, 85 Robert Jones, 90 Lindsey Parks, 98";
var regex = new Regex(@"[A-z]* [A-z]*, [0-9]*");
return regex.Matches(inputStr)
.OfType<Match>()
.Select(p => p.Value.Split(','))
.Select(p => new { Name = p[0], Score = Convert.ToInt32(p[1].Trim()) });
I hope to be helpful for you :)
Upvotes: 1