Ammar Alyousfi
Ammar Alyousfi

Reputation: 4372

This code doesn't write anything in a text file?? c#

THis is the contest of "C:\grades" :

Khaled
80
90
70
Ammar
100
99
100
Wael
43
56
79

and this is the code I used :

StreamReader sr = new StreamReader("C:\\grades.txt");
StreamWriter sw = new StreamWriter("C:\\ava.txt");
string line;
float sum=0;
float avg=0;

while ((line = sr.ReadLine()) != null)
{
    if ((line[0] >= 65 && line[0] <= 90) || (line[0] >= 97 && line[0] <= 122))
    {
        avg = sum / 3;
        if (avg != 0)
            sw.WriteLine(avg.ToString());
        sum = 0;
        avg = 0;
        sw.WriteLine(line);
    }
    else
    {
        sw.WriteLine(line);
        sum += float.Parse(line);
    }
}

This code is to create a text file looks like :

Khaled
80
90
70
80
Ammar
100
99
100
99.66
Wael
43
56
79
59.33

where the added numbers are the averages.

Upvotes: 0

Views: 187

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460158

Maybe this could simplify your task. It shows how to parse the string to a number(i have used Decimal), use Enumerable.Average to get the average and Math.Round to round it:

var userGrades = new Dictionary<string, List<decimal>>();
string currentUserName = null;
foreach (string line in File.ReadLines(sourcePath))
{ 
    decimal grade;
    if (decimal.TryParse(line.Trim(), out grade))
    {
        // line with a grade
        List<decimal> grades;
        userGrades.TryGetValue(currentUserName, out grades);
        if (grades != null) grades.Add(grade);
    }
    else
    {
        // line with the name
        currentUserName = line.Trim();
        if (!userGrades.ContainsKey(currentUserName))
            userGrades.Add(currentUserName, new List<decimal>());
    }
}

using (var writer = new StreamWriter(destPath))
{
    foreach (var ug in userGrades)
    {
        writer.WriteLine(ug.Key);
        foreach(decimal d in ug.Value)
            writer.WriteLine(d);
        decimal roundedAverage = Math.Round(ug.Value.Average(), 2);
        writer.WriteLine(roundedAverage);
    }
}

Note that the using around the StreamWriter ensures that it get closed/disposed what also flushes it's output to the file. I assume that you have missed this.

Upvotes: 0

Dustin Kingen
Dustin Kingen

Reputation: 21245

You need to dispose of the writer properly or it will not flush the output.

string line;
float sum=0;
float avg=0;

using(StreamReader sr = new StreamReader("C:\\grades.txt"))
using(StreamWriter sw = new StreamWriter("C:\\ava.txt"))
{
    while ((line = sr.ReadLine()) != null)
    {
        if ((line[0] >= 65 && line[0] <= 90) || (line[0] >= 97 && line[0] <= 122))
        {
            avg = sum / 3;
            if (avg != 0)
                sw.WriteLine(avg.ToString());
            sum = 0;
            avg = 0;
            sw.WriteLine(line);
        }
        else
        {
            sw.WriteLine(line);
            sum += float.Parse(line);
        }
    }
}

Upvotes: 2

Related Questions