James Elderfield
James Elderfield

Reputation: 2507

ifstream sets failbit on declaration

I don't really understand why this is happening at all. I'm trying to open a file to read some data into my program but failbit gets set instantly, having moved error messages around it seems that failbit actually gets set before I even attempt input.open(). The undeclared variables in the code are globals which live elsewhere (messy but will refine later) Here's the offending function from a larger project:

int read_input()
{
ifstream input;
string value;
int file_complete=0;
int count=0;

if(input.failbit)
    printf("Really?\n");

input.clear();

input.open("Input.txt");

while(!file_complete)
{
    if(input.failbit)
    {
        printf("Reading in set-up value number %d failed.", count+1);
        getchar();
        return 1;
    }
    else if(input.eofbit)
    {
        file_complete=1;
    }

    if(input.get()=='=')
    {
        getline(input, value);

        switch(count)
        {
            case 0:
                n_loci=atoi(value.c_str());
                count++;
                break;
            case 1:
                n_founders=atoi(value.c_str());
                count++;
                break;
            case 2:
                n_self=atoi(value.c_str());
                count++;
                break;
            // Add more cases later
        }
    }
}

input.close();

return 0;
}

This program for me turns out:

Really? Reading in set-up value number 1 failed.

I'm assuming I've done something very stupid but have been at this quite a while now.

P.S I'm compiling with the latest version of g++ on cygwin on top of Windows 7.

Upvotes: 0

Views: 206

Answers (1)

James Elderfield
James Elderfield

Reputation: 2507

OK fixed this myself now:

  • Failbit seems to be set by EOFs in some implementations so instead I switched to using input.good() and consequently all was good.
  • There was also some logical error in my program with the checking for "=" part too as ifstream.get() returns it's value as an integer so I needed to cast them back into chars for comparison.

Upvotes: 1

Related Questions