Search code examples
c#while-loopstreamreader

C# stream reader read line to stor in data


I have sample.txt here:

ABCDEABCDEABCDEABCDE
1000 ABCDEABCDEABCDEABCDE
1001 BCDEABCDEABCDEABCDEA
1002 CDEABCDEABCDEABCDEAB
1003 DEABCDEABCDEABCDEABC
1004 EABCDEABCDEABCDEABCD
1005 AABBCCDDEEABCDEABCDE
1006 ABBCCDDEEAABCDEABCDE
1007 ACBEDADCEBBCDEAABABA
1008 AAAAAAAAAAAAAAAAAAAA
1009 BBBBBBBBBBBBBBBBBBBB
1010 EEEEEEEEEEEEEEEEEEEE
1011 CCCCCCCCCCCCCCCCCCCC
1012 DDDDDDDDDDDDDDDDDDDD
0000 

first line is the standard answer, the following are the student ID (4 digits) and student answers(20 digits). and the requirement is unless student ID =0000, else read the line to array.array[0]=student1 id,array[1]=student 1 answeer. or studentID[0]=student 1 ID, answer[0]=student 1 answer. I am not familiar with while condition with increasing i.

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            int id;
            string line;
            string[] token;


            var lineCount = File.ReadLines("C:\\testresult\\exam.txt").Count();
            Console.WriteLine(lineCount);
            string[] record = new string[lineCount];

            try
            {
                StreamReader sr = new StreamReader("C:\\testresult\\exam.txt");
                line = sr.ReadLine();

                line = sr.ReadLine();
                token = line.Split();
                id = Convert.ToInt32(token[0]);
                while (id != 0)
                {
                    {
                        Console.WriteLine(token[1]);
                        line = sr.ReadLine();
                        token = line.Split();
                        id = Convert.ToInt32(token[0]);
                        for (int i = 0; i < lineCount; i = i + 2)
                        {
                           record[i]=Convert.ToString(id);
                            record[i + 1] = token[1];
                            Console.WriteLine(record[i], record[i + 1]);

                        }
                    }
                }
                sr.Close();
                Console.ReadLine();

            }
            catch { }
        }
    }
}

can anyone advise how to read lines one by one and store the id and token[0] into each element in the array every time?


Solution

  • Let's run through a couple of basic learning points.

    1. Don't do try...catch unless you're going to actually do something with the exception.
    2. StreamReader is IDisposable so should be in a using block
    3. The posted code will iterate through the entire file twice. Not an issue for a small file; but I wanted to point that out.
    4. Try to get into the habit of only declaring variables as close to the 'scope' that they are used in - it makes your code easier to read and maintain (e.g. when moving code around), and there is no performance hit for declaring local variables inside a loop.
    5. String.Split will always give you one item (the zeroth) but you are using the 1st item token[1] without checking whether there is one, and there won't be when Id=0, which would give you an IndexOutOfRangeException.
    6. You have a pair of matched braces for no apparent reason, which can and should be removed (keep your code simple).
    7. You definitely seem confused in terms of having the for loop inside the while loop. Your while loop will be executed for each line in the file except the first one, so you just need to keep count of how many times you've been through the loop.
    8. If you were going to make your code a bit more 'defensive' you could use int.TryParse rather than Convert.ToInt32; but I'm going to assume you're not worried about that.

    So that would give you...

    static void Main(string[] args)
    {
        var records = new List<string>();
        foreach (string line in File.ReadLines("C:\\testresult\\exam.txt").Skip(1))
        {
            var tokens = line.Split();
            int id = Convert.ToInt32(tokens[0]);
            if (id == 0)
            {
                break;
            }
            else if (tokens.Length > 1)
            {
                // It looks like you want the Id and values to be put consecutively in the same array, which doesn't seem very useful.
                // I would have thought a Dictionary<int,string> would be more useful... but here you go.
                records.Add(id.ToString());
                records.Add(tokens[1]);
            }
        }
    
        // If you really want records to be an array you can use "records.ToArray()"
    
        Console.ReadLine();
    }