Jump to content

How do you read from a .txt File??

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Tenacious_TK

Tenacious_TK

    Newbie

  • Members
  • Pip
  • 2 posts
i am doing a project for uni in which i have a .txt file containing some units of measurement and there conversions for example

ounce, gram, 28.0

i need to make a console application in which the user enters an amount then 2 units of measurement the first being what they have and the second being what they want to convert to for example

9, ounce, gram

the program then needs to output how many grams are in 9 ounces

and there are also other units of measurement within this .txt file which may need to be used depending on what the user wants to convert from and to.

basically i do not know how to relate what the user has typed in, in the Console.ReadLine(); to the information in the .txt file

so far i have this:

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

namespace Console Application
{
class Program
{
static void Main(string[] args)
{
//Read in Conversion File

StreamReader sr = new StreamReader("../../Convert.txt");

//Declare Variables
string SAmount;

//Main Program

Console.WriteLine("Please enter an amount follwed by 2 units of measurement eg. 5, ounce, gram:");
SAmount = Console.ReadLine();

}
}
}

any help would be much appreciated as i am completely stumped

Cheers!!

#2
semprance

semprance

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
First, edit your post and wrap the code in tags. It'll make it more readable.

Second, I'm not willing to give you a full piece of source code what with this being an assignment and all.

However, this snippet will read all of the lines from your text file into a List:


    string line;
    List<String> convList = new List<String>();

    while ((line = r.[B]ReadLine[/B]()) != null)
    {
        convList.[B]Add[/B](line);
    }


Hope that helps slightly.

#3
veda87

veda87

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
Here is about how to read a file

string buffer;
            string[] temp;
            FileStream filefs = new FileStream("abc.txt", FileMode.Open);
            StreamReader sr = new StreamReader(filefs);
            buffer = sr.ReadLine();
            // split based on the , followed by spaces
            temp = buffer.Split(', ');
            // temp[0] = 9
           // temp[1] = ounce
           // temp[2] = gram
            int value = (int)Double.Parse(temp[0],System.Globalization.NumberStyles.Integer); // reads the integer
            
Hope this helps you...