samedi 25 février 2017

Can you use a logical operator when evaluating the streamReader.Peek method?

I am filling an array from a file and evaluating whether I am at the end of the file or I have reached the length of my array[100]:

//fill array from file, checking for errors (strings, blanks)
int i = 0;
while (inputFile.Peek() != -1 || i < originalData.Length)
{
    item = inputFile.ReadLine();
    if (!double.TryParse(item, out z)) errors++;
    else originalData[i++] = Convert.ToDouble(item);
}

Results: This is evaluating TRUE every time. If my file has <100 numbers, I get pulled into an infinite loop. Once I've read the last number in my file, it begins to increase my errors counter. If my file has >100 numbers, I get an outOfIndex exception.

I have fixed this problem by breaking up the evaluation:

while (inputFile.Peek() != -1)
{
    if (i < originalData.Length)
    {
        item = inputFile.ReadLine();
        if (!double.TryParse(item, out z)) errors++;
        else originalData[i++] = Convert.ToDouble(item);
    } else break;

Are you not able to use logical operators while evaluating peek? I have also tried:

 !inputfile.EndOfStream()

with the same results.

My program needs to be able to evaluate files of any sizes. Here are two examples of files I am testing with:

Marks.txt - total 106 lines Marks 87.5 54.3 95.0 33.3 76.1 65.9 17.2 83.8 71.0 66.6

90.0 72.2 73.9 69.1

test.txt - total 6 lines title 123 45 6 78 9

Aucun commentaire:

Enregistrer un commentaire