Provided that you assigned fname right, and the compiler would make it hard to do it wrong, that should work. If it's failing, it's because of something other than the way you're calling open().
#include <fstream>
#include <iostream>
class pirate {
private:
int temp[20];
char city[20][25]; // oh, there are 20 sets of data and the name is a maximum of 25 chars long
int hightemp;
int lowtemp;
float average;
char highname[25];
char lowname[25];
public:
//I have no constructor, it caused problems so I got rid of it.
void getfilename(char fname[25]);
void fileread(char fname[25]);
void hsearch( );
void lsearch( );
void asearch( );
void printdata( );
};
usingnamespace std;
pirate data; // _pirate_ is the name of the class. data is an identifer of type _pirate_
// that was the only way I could get it to work, doing functions using "pirate" didn't seem to work.
int main()
{
char fname[25];
data.getfilename(fname);
data.fileread(fname);
return 0;
}
void pirate::getfilename(char fname[15])
{
ifstream fnamefile;
fnamefile.open("filenamehere.txt");
fnamefile >> fname[0];
int fcount = 0;
while(fnamefile)
{
cout << fname[fcount];
fcount++;
fnamefile >> fname[fcount];
}
return;
}
void pirate::fileread(char fname[15])
{
ifstream sourcefile;
sourcefile.open(fname);
if(!sourcefile)
{
cout << "imput failure" << endl;
return;
}
// the part below never gets called. It just reports abck with "imput failure"
int count1 = 0; // keeps track of which data set
int count2 = 0; // count of the loop to find the name.
sourcefile >> reader;
data.city[count1][count2] = reader;
while(sourcefile)
{
count2++;
while(reader != ' ')
{
sourcefile >> data.city[count1][count2];
count2++;
}
sourcefile >> data.temp[count1];
sourcefile >> reader;
}
}
No it doesn't. And I imagine the problem is because the file is not found in the current directory. If you are using MSVC++, this is the solution directory, not the directory with the .exe in it.
I got it to work by calling the function by saying
fileread("a8.txt")
I didn't think that would work, but it did.
I don't really get it, though. Why does passing the name as "name" to a function expecting a char array work, when defining an array and assigning a value to each component then passing that array does not work?