我被赋予了一个简单的任务,我似乎无法弄清楚如何完成它。
我得到了一个文本文件,其中包含员工的姓名和工资率/工时。格式如下:
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/