I am trying to open a file which normally has content, for the purpose of testing i will like to initialize the program without the files being available/existing so then the program should create empty ones, but am having issues implementing it. This is my code originally
void loadFiles() {
fstream city;
city.open("city.txt", ios::in);
fstream latitude;
latitude.open("lat.txt", ios::in);
fstream longitude;
longitude.open("lon.txt", ios::in);
while(!city.eof()){
city >> cityName;
latitude >> lat;
longitude >> lon;
t.add(cityName, lat, lon);
}
city.close();
latitude.close();
longitude.close();
}
I have tried everything i can think of, ofstream, ifstream, adding ios::out all all its variations. Could anybody explain me what to do in order to fix the problem. Thanks!
You have posted code for reading files, not creating empty ones – you need t expand your question in this regard. And what you have posted is not good code for reading. The eof() function detects end of file following a read, not before one – basically, you should almost never use it. Instead, you should test the success of each read:
Also, if you want to create an input stream, why not do so explicitly using an ifstream object:
No need to mess around with ios flags. You should really test if the open worked too: