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?
Let's run through a couple of basic learning points.
try...catch
unless you're going to actually do something
with the exception.IDisposable
so should be in a using
blocktoken[1]
without checking whether there is one, and there won't be when Id=0, which would give you an IndexOutOfRangeException.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.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();
}