I currently have this:
using (StreamReader sr = new StreamReader("answers.txt"))
{
for (iCountLine = 0; iCountLine < 10; iCountLine++)
{
for (iCountAnswer = 0; iCountAnswer < 4; iCountAnswer++)
{
sQuestionAnswers[iCountLine, iCountAnswer] =
}
}
}
My text file is formatted like this (10 lines of text, with 4 items on each line separated by commas):
example, example, example, example
123, 123, 123, 123
I'm not sure what I need after the "=" in the for loop to get it to read and split the contents of the text file into the 2D array.
I'm not sure what I need after the "=" in the for loop
There's also a line missing above it:
var tokens = sr.ReadLine().Split(',');
Now the line with =
would look like this:
sQuestionAnswers[iCountLine, iCountAnswer] = tokens[iCountAnswer];
This doesn't use StreamReader
, but it's short and easy to understand:
string[] lines = File.ReadAllLines(@"Data.txt");
string[][] jaggedArray = lines.Select(line => line.Split(',').ToArray()).ToArray();
Rows are extracted by ReadAllLines
according to newline. Columns values are extracted by calling Split
on every line. It returns jagged array that you can use similarly to multidimensional array, also jagged arrays are generally faster than multidimensional arrays.
string line;
using (var sr = new StreamReader("answers.txt"))
{
while ((line = sr.ReadLine()) != null)
{
for (int iCountLine = 0; iCountLine < 10; iCountLine++)
{
var answers = line.Split(',');
for (int iCountAnswer = 0; iCountAnswer < 4; iCountAnswer++)
{
sQuestionAnswers[iCountLine, iCountAnswer] = answers[iCountAnswer];
}
}
}
}
I'd suggest you to change the approach.
Go over the file using ReadLine() method of a StreamReader class.
Then split the read line using Split(new[]{','}), and this will give you every single record.
And finally the sQuestionAnswers[iCountLine, iCountAnswer] will be: the just Split array's [iCountAnswer]'s record.