[nfbcs] Failing If Statement

Lanie Molinar laniemolinar91 at gmail.com
Fri Oct 27 20:07:39 UTC 2017


Thanks! I took what you said and changed that function a little, and 
everything worked great! That function now looks like:

float readFile(char fileName[])
{
    ifstream fin(fileName);
    if (fin.fail())
    {
       cout << "Error reading file \"" << fileName << "\"\n";
       return 0.0;
    }
    float grade;
    int numGrades = 0;
    float sum = 0.0;
    while (fin >> grade)
    {
       numGrades++;
       sum += grade;
    }
    if (numGrades != 10)
    {
       cout << "Error reading file \"" << fileName << "\"\n";
       fin.close();
       return 0.0;
    }
    else
    {
       fin.close();
       return (sum / numGrades);
    }
}


On 10/27/2017 3:00 PM, Mike Gorse wrote:
> On Fri, 27 Oct 2017, Lanie Molinar wrote:
>
>> Okay, then if that doesn't work,I need to find a way to get rid of 
>> the duplicate error messages in test 5:
> ...
>> Starting Test 5
>>
>> This should yield an error because the file does not exist
>
> Look at your if clauses. It's a good idea to stop trying to do things 
> if your code encounters a fatal error. Ie, why not have your first if 
> clause return from the function if it determines that the file doesn't 
> exist, rather than going on and trying to read from the stream?
>
> -Mike





More information about the NFBCS mailing list