C#流读取器读取行以存储数据

时间:2018-04-17 15:10:22

标签: c# while-loop streamreader

我在这里有sample.txt:

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 

第一行是标准答案,以下是学生证(4位数)和学生答案(20位数)。 并且要求是除非学生ID = 0000,否则读取行到array.array [0] = student1 id,array [1] = student 1 answeer。或studentID [0] =学生1 ID,回答[0] =学生1回答。 随着情况的增加我不熟悉。

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 { }
        }
    }
}

任何人都可以建议如何逐行读取行并将id和token [0]存储到数组中的每个元素中吗?

2 个答案:

答案 0 :(得分:2)

让我们来看看几个基本的学习要点。

  1. 除非你真的要做某事,否则不要做try...catch 除了。
  2. StreamReader为IDisposable,因此应位于using
  3. 发布的代码将遍历整个文件两次。小文件不是问题;但是我想指出这一点。
  4. 尝试养成仅将变量声明为接近它们所使用的“范围”的习惯 - 它使您的代码更易于阅读和维护(例如,当移动代码时),并且没有性能损失在循环中声明局部变量。
  5. String.Split总是会给你一个项目(第0个),但是你正在使用第一个项目token[1]而不检查是否有一个项目,并且当Id = 0时不会有,这会给你一个IndexOutOfRangeException。
  6. 你有一对匹配的括号,没有明显的原因,可以而且应该删除(保持你的代码简单)。
  7. for循环中使用while循环时,你肯定感到困惑。除了第一行之外,文件中的每一行都会执行while循环,所以你只需要计算你循环次数的次数。
  8. 如果你打算让你的代码更“防守”,你可以使用int.TryParse而不是Convert.ToInt32;但我会假设你并不担心。
  9. 这样会给你......

    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();
    }
    

答案 1 :(得分:0)

您可以使用哈希表记录您的数据。 例如:

$(document).ready(function() {


  $('#section-a .answer, #section-b .answer').on('click', function() {
    if ($(this).siblings().hasClass("answerPick") == false) {
      $(this).toggleClass('answer answerPick');
    }

  });

  $('#section-c .answer, #section-d .answer').on('click', function() {
    $(this).toggleClass('answer answerPick');
  });


  $('#submittah').click(function() {
    var q1 = $('#section-a').find('.answerPick').attr('data-url');
    var q2 = $('#section-b  .answerPick').attr('data-url');
    var q3 = $('#section-c  .answerPick').attr('data-url');
    var q4 = $('#section-d  .answerPick').attr('data-url');
    var finalURL = q1 + q2 + q3 + q4;
    window.location.href = finalURL;
  });


});

Ex:如果你想得到ID为1009的学生的回答

//Record data to Hash Table   
Hashtable hash = new Hashtable();

    StreamReader sr = new StreamReader(@"C:\Users\Binh\Desktop\C#\test\exam.txt");
    while(sr.EndOfStream == false)
    {
        string line = sr.ReadLine();

        if(!line.StartsWith("0") && !Regex.IsMatch(line, @"^[A-Z]"))
        {
            string[] info = line.Split(' ');//Split string
            string strudent_id = info[0];
            string student_ans = info[1];
            hash.Add(strudent_id, student_ans);
        }
    }
    sr.Close();

    //Watch the result
    foreach (DictionaryEntry item in hash)
    {
        Console.WriteLine(item.Key + "," + item.Value);
        //OUTPUT:
        //1007,ACBEDADCEBBCDEAABABA
        //1009,BBBBBBBBBBBBBBBBBBBB
        //1010,EEEEEEEEEEEEEEEEEEEE
        //1012,DDDDDDDDDDDDDDDDDDDD
        //1001,BCDEABCDEABCDEABCDEA
        //1002,CDEABCDEABCDEABCDEAB
        //1004,EABCDEABCDEABCDEABCD
        //1006,ABBCCDDEEAABCDEABCDE
        //1008,AAAAAAAAAAAAAAAAAAAA
        //1011,CCCCCCCCCCCCCCCCCCCC
        //1000,ABCDEABCDEABCDEABCDE
        //1003,DEABCDEABCDEABCDEABC
        //1005,AABBCCDDEEABCDEABCDE
    }