这段代码不会在文本文件中写任何东西? C#

时间:2013-04-19 11:57:20

标签: c# file

这是“C:\ grade”的比赛:

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

这是我使用的代码:

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);
    }
}

此代码用于创建文本文件,如下所示:

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

其中添加的数字是平均值。

2 个答案:

答案 0 :(得分:2)

您需要正确处理编写器,否则不会刷新输出。

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);
        }
    }
}

答案 1 :(得分:0)

也许这可以简化你的任务。它显示了如何将字符串解析为数字(我已使用Decimal),使用Enumerable.Average获取平均值,Math.Round将其舍入:

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);
    }
}

请注意,using周围的StreamWriter可确保关闭/处置它还将其输出刷新到文件中。我假设你错过了这个。