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...

#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);

cout << "Enter again the name of an existing text file: ";
cin.get (new_file,20);
  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
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....

since the fstream is global (bad programming habbit) after closing the file you have to clear the errors.


A better solution is to make the fstream object local to the function, or pass a reference to it.

You might want to try to flush stdin. When you're prompt for the second filename, the program might automatically input excess garbage off of the stdin buffer. You might also want to try writing a function that'd simply fgets character garbage off stdin. Sometimes the newline character will remain in this buffer and'll act as a ENTER key pressed when inputted. To flush simply use this code:


For more information regarding fflush (i.e which header files you need to include) simpy request for the fflush manual:

Lintux/root/:> man fflush

Good luck, LamaBot