I am doing a school project, working on a program which is used to analyze and display information from a text file. The skeleton program was written for me (I'm assuming by the instructor) and I have not modified it yet.
My crash occurs after I specify a text file for the program to open, whether the file exists or not. It only happens on my main PC which is running Vista. It does not happen on my laptop or on the PCs in the computer lab, which are running XP. The exception code in Windows' "This program has stopped working," box is c0000005. I'm guessing that makes it hard to troubleshoot because that error code is not very specific.
Here are the lines which invoke the sub-function to open the file:
1 2 3
cin>>filename;
//calls data_in to input information from gas prices data file
int flag=data_in(filename,nStations, nWeeks);
Here is the code I suspect does not agree with Vista:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int data_in(char* filename, int nStations,int nWeeks)
{
// variable declaration and initialization
FILE *data_ptr;//data file pointer
int nC,nR, nWC;//column counter, row counter, week counter, number of stations
// open datafile
data_ptr = fopen(filename, "r" );
printf("Opening data file %s\n", filename);
if (data_ptr == NULL)
{
printf("\nFile failed to open\n");
cout<<"\nPress enter to continue\n";
scanf("%c",&next);
scanf("%c",&next);
return 0;
}
else
{
The rest of the code in the data_in function is for displaying the data. I do not think it is relevant for troubleshooting because the crash occurs even if I specify a non-existent file. Has anyone seen this type of error before? Any ideas on how to fix it? I am quite happy with Vista on my machine. If I have to, I will test programs on my laptop.
The above code looks like mainly C with one or two lines C++
first I would get rid of the scanf() calls, they are tricky - if a user enters something unexpected they go bananas, instead use something simple like C++'s getline or fgets/gets if u want to continue programming C
you should declare filename as a string instead of char*
i.e.
1 2
string filename;
cin>>filename
and in your function
1 2 3 4 5
int data_in( const string &filename, int nStations, int nWeeks )\
{
...
data_ptr = fopen( filename.c_str(), "r" );
...
instead of using FILE use the C++ ifstream, although nothing wrong with using FILE its more convenient to use ifstream
also don't declare variables at the top of the function, declare them where they are used.