Search code examples
c++ifstreamistream

Cannot extract data from command line as expected


I have a courses0.dat file with a single 4 on line 1 that I want to extract with my ifstream program:

void processEnrollments (std::istream& courseFile);

int main (int argc, char** argv)
{

// Take input and output file names from the command line
ifstream coursesIn (argv[1]);

return 0;
}

void processEnrollments (istream& courseFile)
{
int numCourses;
courseFile >> numCourses;

cout << numCourses;

// Create the arrays we need
//!! Insert your code here
}

when I run

program courses0.dat

my test is cout'ing a 32767 instead of a 4. My .dat file is in the same directory as my executable.

any clue as to what is going on?

thanks


Solution

  • Check for errors! Try to use the full path to the file when you pass it as an argument.

    My guess is courseFile >> numCourses; fails because ifstream coursesIn (argv[1]) doesn't find or can't access the file.

    Try this

    if( courseFile >> numCourses )
        cout << numCourses;
    

    Does it output anything then?