I am currently programming in Linux using the g++ compiler. I was trying to make an open function that would open a file and store its contents in a 2d vector. I was successful at doing the said function. I thought I was done with it, but I realized that I can sucessfully call the function once in the prgrogram, whenever I call it again, it would not open any file. So I thought there might be wrong with my implementation, so i just just opening a file and then just output it to the screen, only one file is sucessfully opened and only one output is shown. Here's the code, can anybody help in pinpointing the problem.
here's the code I did, trying to find out what's wrong, I was only prompted to enter the filename once, then the next one somewhat bypassed...
//try.cpp
#include <iostream>
#include <fstream>
using namespace std;
char filename[20], new_file[20];
fstream is;
int openFile(char file[20]){
char c;
if (is.open (file)){ // open file
while (!is.eof()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
cout << c;
}
is.close(); // close file}
else cout<< "error opening file";
return 0;
}
int main () {
//char c, str[256], newfile[256];
cout << "Enter the name of an existing text file: ";
cin.get (filename,20);
openFile(filename);
cout << "Enter again the name of an existing text file: ";
cin.get (new_file,20);
openFile(new_file);
return 0;
}
here's the output, after compiling this using g++ -o try try.cpp:
[root@192~]# ./try
Enter the name of an existing text file: file01.txt
new file
here
hahahaÿEnter again the name of an existing text file: [root@192~]
the program will not let me type the filename of the next file that I want to open...
I hope someone would be able to help me....thanks in advance....