user1550607 user1550607 - 1 year ago 93
C# Question

Parsing a file with strings and integers c#

I have been given a simple task, that I cannot seem to figure out how to accomplish it.

I have been given a text file that has both names and pay rate/hours of employees. The format is as follows:

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

My task is to write a program that uses StreamReader to pull the data from a text file, then print the employees name, and calculate the total pay by multiplying the rate and hours.

I know how to split the line with a .Split method, however I can't seem to figure out how to seperate the names from the doubles/ints. My parse methods always come back with a format error because it reads the strings first. I am completely stuck.

Here is my code so far, any help or guidance would be appreciated.

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;

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

Ria Ria
Answer Source

Use Decimal.Parse and read two line:

    name = myfile.ReadLine();
    if (name != null)
        // read second line
        var nums = myfile.ReadLine();
        if (nums != null)
            string[] payNums = nums.Split(new[] {' '});
            Console.WriteLine("{0}: {1}", 
                              * Decimal.Parse(payNums[1]));
} while (name != null);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download