CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 19
  1. #1
    Join Date
    Oct 2015
    Posts
    38

    Reading information from a text file code help

    So I've been learning a lot about C# recently and learned a lot from making several practice programs based on mathematical equations and I wanted to try something else involving text files and C#.
    I've written up some code but it is giving me a LOT of errors and I don't really understand why.
    I'm using the "using System.IO;" which I initially forgot about presuming it would fix my problem. I'll post what I am trying to do and then along with my code of what I am doing.

    1: Read in a text file [any one on any computer] (from the debug location).
    2: Read each value separated by a comma and turn each of these values into a double that I can use in a calculation or just anything.
    3: For example, add the 8th value in the text file to the 11th value, just to test if it works.

    Text file content and exact layout/format:
    11
    0.0,23.0,15.0
    1.0,23.0,14.0
    2.0,23.0,14.0
    3.0,22.0,14.0
    8.0,20.0,14.0
    9.0,20.0,15.0
    10.0,19.0,14.0
    12.0,12.0,7.0
    18.0,11.0,7.0
    23.0,10.0,7.0
    29.0,10.0,6.0


    My code (which isn't doing what it is supposed to be doing for some reason and its driving me insane)

    Code:
    static void ReadData( string DataFile)
    {
    string s;
    System.IO StreamReader inputFile = new System.IO StreamReader(DataFile)
    
    s = inputFile.ReadLine();
    int noDataLines = int.Parse(s);
    
    Console.WriteLine("the file {0} contains {1} lines of data", DataFile, noDataLines);
    
    double [][] data = new double[noDataLines][];
    double [] xy;
    
    string[]ss;
    for(int = 0, i< noDataLines; i++)
    {
    s = inputFile.ReadLine();
    s.Split(',');
    Console.WriteLine(s);
    xy = new double[]{ double.Parse(ss[0], double.Parse(ss[1])};
    
    }
    
    
    
    while(!inputFile.EndOfStream)
    
    { s = inputFile.ReadLine();
    Console.WriteLine(s);
    }
    inputFile.Close();
    }
    Any ideas? help would be much appreciated.

  2. #2
    Join Date
    Oct 2015
    Posts
    38

    Re: Reading information from a text file code help

    here is the full code, made a small semicolon error but the rest is still messy.
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace Assignment_3
    {
     class Program
     {
     static void Main(string[] args)
     {
     {
     string s;
     System.IO StreamReader inputFile = new System.IO StreamReader(DataFile);
     s = inputFile.ReadLine();
     int noDataLines = int.Parse(s);
     //this is just to test out the files
     Console.WriteLine("the file {0} contains {1} lines of data", DataFile, noDataLines);
     double[][] data = new double[noDataLines][];
     double[] xy;
     string[] ss;
     for (int = 0, i < noDataLines; i++)
     {
     s = inputFile.ReadLine();
     s.Split(',');
     Console.WriteLine(s);
     xy = new double[] { double.Parse(ss[0], double.Parse(ss[1])};
     }
     while (!inputFile.EndOfStream)
     {
     s = inputFile.ReadLine();
     Console.WriteLine(s);
     }
     inputFile.Close();
     }
     }
     }

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Reading information from a text file code help

    Can you format your code when you paste it in? No wonder you're having problems tracking issues down, if you're trying to figure out code that's formatted like that.

    Not trying to be harsh, but code that is well formatted helps you spot errors.

  4. #4
    Join Date
    Oct 2015
    Posts
    38

    Re: Reading information from a text file code help

    Quote Originally Posted by Arjay View Post
    Can you format your code when you paste it in? No wonder you're having problems tracking issues down, if you're trying to figure out code that's formatted like that.

    Not trying to be harsh, but code that is well formatted helps you spot errors.
    Sorry and non taken My code wasn't formatted the way it was shown above I think that was my fault when I copy and pasted it.
    I've added in "using System.IO;" now and fixed one error with the brackets but that has only reduced an error. This is the EXACT state of the code I am working with
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    
    namespace Assignment_3
    {
        class Program
        {
            static void Main(string[] args)
            {
                {
                    string s;
                    System.IO StreamReader inputFile = new System.IO StreamReader(DataFile);
    
                    s = inputFile.ReadLine();
                    int noDataLines = int.Parse(s);
                    //this is just to test out the files
                    Console.WriteLine("the file {0} contains {1} lines of data", DataFile, noDataLines);
    
                    double[][] data = new double[noDataLines][];
                    double[] xy;
    
                    string[] ss;
                    for (int = 0, i < noDataLines; i++)
                    {
                        s = inputFile.ReadLine();
                        s.Split(',');
                        Console.WriteLine(s);
                        xy = new double[] { double.Parse(ss[0], double.Parse(ss[1])};
    
                    }
    
                    while (!inputFile.EndOfStream)
    
                    {
                        s = inputFile.ReadLine();
                        Console.WriteLine(s);
                    }
                    inputFile.Close();
                }
    
            }
        }
    }
    It says "System.IO" is a namespace but used as a type" I've no idea what that means. that is one of many errors I am experiencing. Will I write out each error in hope that it will be explained? thanks

  5. #5
    Join Date
    Oct 2015
    Posts
    38

    Re: Reading information from a text file code help

    I've decided to take a new approach and completely edit my code.
    Here is my new code:
    Code:
     using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    
    namespace Assignment_3
    {
        class Program
        {
            static void Main(string[] args)
            {
                {
                    //creates a streamreader that allows lake1data.txt to be read in
                    StreamReader testing = new StreamReader("lake1data.txt");
                    //creates an empty variable called "line"
                    string line = "";
                    //while line is not null, read each line
                    while (line != null)
                    {
                        line = testing.ReadLine();
                        if (line != null)
                            //if line is not null, write "line" to the console.
                            Console.WriteLine(line);
    
                    }
                    testing.Close();
                    Console.ReadKey();
                }
            }
        }
    }
    Now what I am trying to do is turn each of the numbers in the text file to either 2 things.
    1: Each value is an individual double
    2: An Array containing all the values that are in the text file.

    Name:  display.jpg
Views: 171
Size:  21.7 KB

    this is the contents of the text file when printed to screen. Now can somebody perhaps help me sort it into arrays?

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Reading information from a text file code help

    Quote Originally Posted by King_Silver View Post
    Sorry and non taken My code wasn't formatted the way it was shown above I think that was my fault when I copy and pasted it.
    I've added in "using System.IO;" now and fixed one error with the brackets but that has only reduced an error. This is the EXACT state of the code I am working with
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    
    namespace Assignment_3
    {
        class Program
        {
            static void Main(string[] args)
            {
                {
                    System.IO StreamReader inputFile = new System.IO StreamReader(DataFile);
            }
        }
    }
    It says "System.IO" is a namespace but used as a type" I've no idea what that means. that is one of many errors I am experiencing. Will I write out each error in hope that it will be explained? thanks
    The problem is with the line of your code that I left in above. When you declare a 'using' statement at the top of your code, there's no need to explicitly include the namespace when you new up the [streamreader] class.

    That wasn't your mistake - your mistake was to have a space between the namespace and the class instead of a period (i.e. you had System.IO StreamReader when you should have had System.IO.StreamReader).

    Besides all this, VisualStudio will help you track down these issues, if you know how. The next time you get a compiler error, double click on the 1st error in the Errors Window and it will take you to the line of code with the problem. Fix that error and recompile. Now it will take you to the error (or close to it), but you may not know what the error is. At first it's hard to figure out what the error means. So copy the error and search for it in bing or google. Don't worry after a few times, you'll be able to spot the errors and know what they mean.

    Visual Studio is also helpful when resolving namespaces. Like if am using StreamReader what using assembly do I need to include? As long as the assembly is included in your project references (and for these type of simple study programs they often are), Visual Studio can resolve it for you. To try it, remove the using declaration... using System.IO; from your code.

    You'll get a squiggly line on the StreamReader in your code. Right-click on the StreamReader in your code, and choose 'Resolve'. It will automatically add the 'using System.IO;' statement to your code.

  7. #7
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Reading information from a text file code help

    Quote Originally Posted by King_Silver View Post
    I've decided to take a new approach and completely edit my code.
    Here is my new code:
    Code:
     using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    
    namespace Assignment_3
    {
        class Program
        {
            static void Main(string[] args)
            {
                {
                    //creates a streamreader that allows lake1data.txt to be read in
                    StreamReader testing = new StreamReader("lake1data.txt");
                    //creates an empty variable called "line"
                    string line = "";
                    //while line is not null, read each line
                    while (line != null)
                    {
                        line = testing.ReadLine();
                        if (line != null)
                            //if line is not null, write "line" to the console.
                            Console.WriteLine(line);
    
                    }
                    testing.Close();
                    Console.ReadKey();
                }
            }
        }
    }
    Now what I am trying to do is turn each of the numbers in the text file to either 2 things.
    1: Each value is an individual double
    2: An Array containing all the values that are in the text file.

    Name:  display.jpg
Views: 171
Size:  21.7 KB

    this is the contents of the text file when printed to screen. Now can somebody perhaps help me sort it into arrays?
    See msdn for String.Split. This class will split out a string into components by the delimiter you specify. In your case, you would use a comma as the delimiter. Split returns an array of strings that contain the contents between the specified delimiter. You can use the Count property to determine the count of items. This helps you because the single item will have a count of 0 (and the other lines should have a count of 3).

  8. #8
    Join Date
    Oct 2015
    Posts
    38

    Re: Reading information from a text file code help

    Made an array now, this is what it looks like:
    Code:
     string filename = "lake1data.txt";
                    //creates a streamreader that allows lake1data.txt to be read in
                    StreamReader InputFile = new StreamReader(filename);
    
                    // the string variable to store a line of the file
                    string s;
                    // declare a string array that will contain the array of sub-strings
                    string[] ss;
                    // read the file line-by-line until the EOF is reached
                    while (!InputFile.EndOfStream)
                    {
                        // read in the next line of the file
                        s = InputFile.ReadLine();
                        // use the Split() method to divide the string into sub-strings,
                        // delimited at a space or comma
                        // ignore blank sub-strings
                        ss = s.Split(new char[] { ' ', ', ' }, StringSplitOptions.RemoveEmptyEntries);
                        // write out each sub-string to the console
                        for (int i = 0; i < ss.Length; i++)
                            Console.WriteLine(ss[i]);
    
                        Console.WriteLine("the 4th value of the text file is {5}", ss[0]);
                    }
    
                    InputFile.Close();
    getting an error on this piece of code:
    Code:
     ss = s.Split(new char[] { ' ', ', ' }, StringSplitOptions.RemoveEmptyEntries);
    it says: "too many characters in character literal"

    The last line about the "console.writeline" is just to test if the values of the arrays are in the correct order and if they saved in the right positions to begin with. Is this a correct approach to the problem?

  9. #9
    Join Date
    Oct 2015
    Posts
    38

    Re: Reading information from a text file code help

    Fixed it, however there is still a problem! Uploading the picture.
    Name:  waahhhh.jpg
Views: 158
Size:  19.6 KB

  10. #10
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Reading information from a text file code help

    The String.Formatter placeholders like {0}, {1}, etc are zero based. So if you have a string to format and only one variable, {5} isn't correct.

    Also ss[0] only returns the first item in the array - you probably meant to use an i there.

  11. #11
    Join Date
    Oct 2015
    Posts
    38

    Re: Reading information from a text file code help

    Quote Originally Posted by Arjay View Post
    The String.Formatter placeholders like {0}, {1}, etc are zero based. So if you have a string to format and only one variable, {5} isn't correct.

    Also ss[0] only returns the first item in the array - you probably meant to use an i there.
    Sorry that was stupid of me haha I fixed that last night thanks for pointing that out. I've done that however I am left with 2 slight problems.
    1: Name:  update1.png
Views: 166
Size:  11.3 KB
    that is my console output

    2: In my code, where I have changed the ss[0] to an ss[i] it is telling me "the name i does not exist in the current context"

    Code:
    string filename = "lake1data.txt";
                    //creates a streamreader that allows lake1data.txt to be read in
                    StreamReader InputFile = new StreamReader(filename);
    
                    // the string variable to store a line of the file
                    string s;
                    // declare a string array that will contain the array of sub-strings
                    string[] ss;
                    // read the file line-by-line until the EOF is reached
                    while (!InputFile.EndOfStream)
                    {
                        // read in the next line of the file
                        s = InputFile.ReadLine();
                        // use the Split() method to divide the string into sub-strings,
                        // delimited at a space or comma
                        // ignore blank sub-strings
                        ss = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        // write out each sub-string to the console
                     
                        for (int i = 0; i < ss.Length; i++)
                            Console.WriteLine(ss[i]);
    
                        Console.WriteLine("the 1st value of the text file is {0}", ss[i]);
                    }
    
                    InputFile.Close();
    EDIT: Trying to make
    "11,0.0,23.0,15.0" the first 4 values in the array and so on...

  12. #12
    Join Date
    Oct 2015
    Posts
    38

    Re: Reading information from a text file code help

    Disregard the previous post I got it working thanks for the clarification.
    Code:
      string filename = "lake1data.txt";
                    //creates a streamreader that allows lake1data.txt to be read in
                    StreamReader InputFile = new StreamReader(filename);
    
                    // the string variable to store a line of the file
                    string s;
                    // declare a string array that will contain the array of sub-strings
                    string[] ss;
                    // read the file line-by-line until the EOF is reached
                    while (!InputFile.EndOfStream)
                    {
                        // read in the next line of the file
                        s = InputFile.ReadLine();
                        // use the Split() method to divide the string into sub-strings,
                        // delimited at a space or comma
                        // ignore blank sub-strings
                        ss = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        // write out each sub-string to the console
                     
                        for (int i = 0; i < ss.Length; i++)
                            Console.WriteLine("The values stored in the text file in order are: {0}",ss[i]);
    
                    }
    
                    InputFile.Close();
    It prints out each value from the text file now one by one as I wanted

    Now if I want to add, for example the 10th value IN the string to the lets say, 12th value IN the string how do I do that?
    How do I convert these numbers to doubles/ints that can be used in a made up formula for example:

    "value10*value3 / value8" in the text file
    Last edited by King_Silver; November 29th, 2015 at 07:33 AM.

  13. #13
    Join Date
    Oct 2015
    Posts
    38

    Re: Reading information from a text file code help

    New code incoming!
    Code:
     string FileName = "lake1data.txt";
    
                using (StreamReader FileReader = new StreamReader(FileName))
                {
                    // Read the size of the array
                    int ArraySize = Convert.ToInt32(FileReader.ReadLine()); 
    
                    double[,] Values = new double[ArraySize, 3]; // This is called a multidimensional array -> [][] is a jagged array
    
                    for (int i = 0; 0 < ArraySize; i++)
                    {
                        string[] LineComponents = FileReader.ReadLine().Split(','); // Read the next line and split it
    
                        for (int j = 0; j < 3; j++)
                        {
                            Values[i, j] = Convert.ToDouble(LineComponents[j]); // Loop through each LineComponent, convert it to a double and store it in the array
                        }
                    }
    
                    //print the array to the console
    
                    Console.WriteLine("The size of the array is: " + ArraySize);
    
                    for (int i = 0; 0 < ArraySize; i++)
                    {
                        Console.Write("The value of i: ");
    
                        for (int j = 0; j < 3; j++)
                        {
                            Console.Write(Values[i, j] + ", ");
                        }
    
                        Console.WriteLine();
                    }

    Name:  errroorr.jpg
Views: 162
Size:  25.7 KB


    What it should be doing: reading in the numbers from the text file and converting them to doubles then storing them in the array.
    This way I can use these values stored in the array for calculations or anything else I want right?

  14. #14
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Reading information from a text file code help

    You need to check for EndOfStream on each file line like your earlier code did.

  15. #15
    Join Date
    Oct 2015
    Posts
    38

    Re: Reading information from a text file code help

    Quote Originally Posted by Arjay View Post
    You need to check for EndOfStream on each file line like your earlier code did.
    you mean the part of my earlier code which was like
    "while (!InputFile.EndOfStream)"


    Code:
     using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    namespace ConsoleApplication7
    {
        class Program
        {
            static void Main(string[] args)
            {
                string FileName = "lake1data.txt";
    
                using (StreamReader FileReader = new StreamReader(FileName))
                {
                    // Read the size of the array
                    int ArraySize = Convert.ToInt32(FileReader.ReadLine()); 
    
                    double[,] Values = new double[ArraySize, 3]; // This is called a multidimensional array -> [][] is a jagged array
    
                    while (!FileReader.EndOfStream)
                    {
    
                        for (int i = 0; 0 < ArraySize; i++)
                        {
                            string[] LineComponents = FileReader.ReadLine().Split(','); // Read the next line and split it
    
                            for (int j = 0; j < 3; j++)
                            {
                                Values[i, j] = Convert.ToDouble(LineComponents[j]); // Loop through each LineComponent, convert it to a double and store it in the array
                            }
                        }
                    }
                    FileReader.Close();
    
    
                    // Now let's print the array to the console
    
                    Console.WriteLine("The size of the array is: " + ArraySize);
    
                    for (int i = 0; 0 < ArraySize; i++)
                    {
                        Console.Write("The value of i: ");
    
                        for (int j = 0; j < 3; j++)
                        {
                            Console.Write(Values[i, j] + ", ");
                        }
    
                        Console.WriteLine();
                    }
                }
            }
        }
    }
    I've added it in but there has been no change in what is appearing in this pictureName:  errroorr.jpg
Views: 148
Size:  25.7 KB

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured