c# - 用字符串和整数解析文件c#

标签 c# streamreader

我被赋予了一个简单的任务,我似乎无法弄清楚如何完成它。

我得到了一个文本文件,其中包含员工的姓名和工资率/工时。格式如下:

Mary Jones
12.50 30
Bill Smith
10.00 40
Sam Brown
9.50 40

我的任务是编写一个程序,使用 StreamReader 从文本文件中提取数据,然后打印员工姓名,并通过将费率和小时数相乘来计算总工资。

我知道如何使用 .Split 方法拆分行,但我似乎无法弄清楚如何将名称与 double /整数分开。我的解析方法总是返回格式错误,因为它首先读取字符串。我完全卡住了。

到目前为止,这是我的代码,如有任何帮助或指导,我们将不胜感激。

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace lab21
{
    class Program
    {
        static void Main(string[] args)
        {

            StreamReader myfile = new StreamReader("data.txt");
            string fromFile;

            do
            {
                fromFile = myfile.ReadLine();
                if (fromFile != null)
                {
                    string[] payInfo = fromFile.Split( );
                    double wage = double.Parse(payInfo[0]);
                    int hours = int.Parse(payInfo[1]);
                    Console.WriteLine(fromFile);
                    Console.WriteLine(wage * hours);
                }
            } while (fromFile != null);
        }
    }
}

最佳答案

您只在循环中读取一行。员工记录似乎由两行 组成 - 因此您需要在每次迭代时都阅读它们。 (或者你可以跟踪你在哪一行,但这会很痛苦。)我会重写循环如下:

string name;
while ((name = reader.ReadLine()) != null)
{
    string payText = reader.ReadLine();
    if (payText == null)
    {
        // Or whatever exception you want to throw...
        throw new InvalidDataException("Odd number of lines in file");
    }
    Employee employee = ParseTextValues(name, payText);
    Console.WriteLine("{0}: {1}", employee.Name, employee.Hours * employee.Wage);
}

然后有一个单独的方法来解析这两个值,这样会更容易测试。

在解析时,请注意您应该使用 decimal 而不是 double 来表示货币值。

关于c# - 用字符串和整数解析文件c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11663585/

相关文章:

c# - 使用 ISO C++ 回调注册委托(delegate)函数(在单声道上)

c# - 检查实体是否在 Code First 中的其他实体中有引用

c# - 从 Raspberry Pi 连接到 SQL Server 会导致错误 35(在登录前握手期间)

c# - 如何在 .net 核心中获取 HttpRequest 主体?

c# - 如何逐行读取 StreamReader 文本

C# process.Kill 不会立即停止正在运行批处理文件的进程

c# - BackgroundWorker 循环中的方法更新进度条

javascript - DotNet Highcharts - 隐藏特定图例标签

c# - 在 C# 中,如何复制具有任意编码的文件,逐行读取,而不添加或删除换行符

c# - 如何在不读取整个文件的情况下找出文件有多少个字符?