-3

Possible Duplicate:
How to stop C++ console application from exiting immediately?

I'm using fstream to gather an input file from the user. Unfortunately, the console only displays briefly.

string filename;
cout << "input file" << endl ;

getline(cin,filename);

ifstream inputfile;
inputfile.open(filename);

char file_character ;
int counter = 0;

while (inputfile>> file_character) {

    inputfile.get(file_character);
    cout << file_character;

    //not what I'm totally doing but instead a quick example
    if (file_character == 'a')
    {
        counter++;
    }
}
cout << counter << endl;
inputfile.close();
return 0;

I need to read every letter from the input file and do a number of checks on each of these characters. Why won't my console stay open?

Community
  • 1
  • 1
user1727433
  • 39
  • 1
  • 6

2 Answers2

1

You can try launching your program from the console. Alternatively, you can pause your program before exiting main: for example, you can wait for user to enter a character, or set a time delay for a couple of seconds.

By the way, you have a bug in your program. while (inputfile >> file_character) already reads character into the variable, so when you go to inputfile.get(file_character) you read again and thus lose half of your input.

prazuber
  • 1,352
  • 10
  • 26
0

Using windows, the console closes as the program exits.

append system("Pause"); at the end of your program and it will prompt for a key to be pressed before exiting.

An universal solution (which would work on any system), is to read a char from the user using std::getchar(); in place of windows exclusive system("pause");

ArtemStorozhuk
  • 8,715
  • 4
  • 35
  • 53
tomahh
  • 13,441
  • 3
  • 49
  • 70