Hi

I currently have a textfile with different types of unit measurements -> from, to, factor (E.g. ounce, gram, 28.0)

So far i've written this:

            string from, to, x, y;
            double factor, amount, output;
            string[] splitData = new string[2];

            StreamReader reader = new StreamReader("Filename.txt");
            string[] data = reader.ReadToEnd().Split(',');

How would i go abouts looping this entire data and storing each bit for further use?

Recommended Answers

All 23 Replies

Perhaps this recent post can help you out. It discusses a while loop to read a file line by line.

Read the discussion but they go onto discussing a 'foreach' option, which would require the File.ReadAllLines method & i wish to read Line by Line

I would proceed as follows: Make a class or struct to contain your conversions (from,to,factor)
Then make a List<Myconversions> MyConvList.
Now read your file, line by line using a while loop and fill up your List.
If all this does not make to much sense, please let us know.

Thank you, I've created a class that contains the conversions like you said, made a list but I am not sure on how i would write the while loop (Inside the brackets), this is what i have so far:

class myConversions
    {
        public string unitFrom;
        public string unitTo;
        public double factor;

    class Program
    {
        static void Main(string[] args)
        {
            string line, from, to, x, y;
            double factor, amount, output;
            string[] splitData = new string[2];

            StreamReader reader = new StreamReader("Filename.txt");
            string[] data = reader.ReadToEnd().Split(',');
            List<myConversions> convertData = new List<myConversions>();

            while ((line = reader.ReadLine()) != null)
            {
            }

Well this is wath I came up with in a Form app but you could translate it to a Console app.

namespace WindowsFormsApplication9
{
    public struct MeasureConversion
    {
        public string from;
        public string to;
        public double factor;
    }

    public partial class Form1 : Form
    {
        List<MeasureConversion> ConvertList = new List<MeasureConversion>();

        public Form1()
        {
            InitializeComponent();
            FillList();
        }

        public void FillList()
        {
            string line;
            string[] splitData;
            StreamReader reader = new StreamReader("Filename.txt");

            while ((line = reader.ReadLine()) != null)
            {
                splitData = line.Split(',');
                MeasureConversion MC = new MeasureConversion();
                MC.from = splitData[0];
                MC.to = splitData[1];
                MC.factor = Convert.ToDouble(splitData[2]);
                ConvertList.Add(MC);
            }
        }
    }
}

Success!

Thank you, I'll let you know how i get on fairly soon..

After the while loop, it's just obtaining user input and producing if statements to see whether they match the data right?

You may need to use (among others)Find or IndexOf methods from the List class Click Here

Currently have:

    /* This class allows the storage of all the data from the text file */
    class myConversions
    {
        public string unitFrom;
        public string unitTo;
        public double factor;

        class Program
        {
            static void Main(string[] args)
            {
                string line, from, to;
                double factor, amount, output;

                List<myConversions> convertData = new List<myConversions>();
                StreamReader reader = new StreamReader("File.txt");
                string[] splitData;


                while ((line = reader.ReadLine()) != null)
                {
                    splitData = eachLine.Split(',');
                    myConversions dataFile = new myConversions();
                    dataFile.measurementFrom = splitData[0];
                    dataFile.measurementFrom = splitData[1];
                    dataFile.factor = Convert.ToDouble(splitData[2]);
                    ConvertData.Add(dataFile);
                }

                while (true)
                {
                    Console.WriteLine("Please enter an amount, the unit from & the unit to: ");
                    Console.WriteLine();
                    string input = Console.ReadLine();

                    string[] measurements = input.Split(',',',', '/', ',');
                    amount = Convert.ToDouble(measurements [0]);
                    from = measurements[1].ToLower().Trim();
                    to = measurements[2].ToLower().Trim();

                    bool foundUnits = false;
                    factor = 0;

Not sure how to set my "for-loop" after this part -> the for loop checks all the data stored in the list, and will lead to an If statement where:

IF (myConversions.unitFrom == from && myConversions.unitTo == to)
       { 
            factor = myConversions.factor;
            foundUnits = true;
            break;
       }

This then activates the if statement to calculate the output value and return it to the user..

Why are you nesting your main program class in your myConversions class? Your setup for the moment will cause a new myConversions object from your original myConversions object, which will also give you main program object etc.
Also on line 22 should it not read: splitData = line.Split(',');

Quoted Text Here
Also on line 22 should it not read: splitData = line.Split(',');

Yes sorry

Quoted Text Here
Why are you nesting your main program class in your myConversions class?

Which part are you referring to? I'm relatively new to C# and do not understand what you mean ;s

Make your myConversions class like this

class myConversions
    {
        public string unitFrom;
        public string unitTo;
        public double factor;
        }

Then continue with:
line 8: class program . . .

Oh forgot the closing bracket, thank you :)

I'm still unsure on how i would go abouts setting a 'for loop' which would look through the data within 'myConversions' where the data is placed (This for loop will lead on to the IF statement i wrote about a couple of posts ago)

Remove lines 41 and 42 in one of your previous posts, they are no longer needed.
Also, forget about if and for statements.
Just add this line:
myConversions Result = ConvertData.Find(delegate(myConversions mc) { return mc.from == from && mc.to == to; });
Now all you have to do is multiply the amount with Result.factor if a conversion is found.
This may all look a bit creepy at first. Certainly if you're a beginner(I was terrified!)
But read here about predicate delegates and here about the List<T>.Find method. Success!

Hello, i've followed your guidelines carefully, using output = Result.factor x amount; as my calculation method, when i ran the program, it did not actually read through all my lines, just the first line, I'm not too sure what's wrong..

Also, how would i go abouts producing a console.writeline message if the conversion does not exist (the Return mc.from == from && mc.to == to;}) do not match the ones provided in the datafile

Did you have a look in the debugger at your dataFile variable? What does it look like after adding say 3 myConversions?

the while (true) allows an unending loop, so the console will just carry on going, however, i cannot read all my data file lines, it only reads the first line.

the layout of my datafile is just:

from,to,factor
from,to,factor
from,to,factor

I ran the debugger & all it said was 'NullReferenceException unhandled', the .find worked for my first line of the data file, but it does not read & look at the rest of the files on new lines (there are more than 3 different types of conversions).

Im not sure whether i wrote something wrong earlier in my code :s?

If possible, could you send me your code you have so far? And where did you set your breakpoint?

Solved

The code above runs fine for the first line for converting the first line of the textfile, but it does nt allow me to convert any other forms of measurements. the problem occurs at output = Results.factor x amount where the nullException i mentioned earlier occurs

Line 23,24 you use measurementFrom and ...To instead of unitFrom etc. Did you ever ran your app?

Wow silly mistakes... it does work, Thank you very much :)

Glad to help, perhaps you could mark this thread as solved?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.