c++visual-c++freopen

when using freopen() in visual studio c++ system("pause") is not working


I was trying to read from a file in vs17. But here system("pause") isn't working. The console window here just pops up and vanishes. The input.txt file contains only one integer.

#include<iostream>
#include<stdio.h>
#include<cstdio>
#pragma warning(disable:4996)
using namespace std;
int main()
{
    freopen("input.txt", "r", stdin);
    int n;
    cin >> n;
    cout << n << endl;
    system("pause");
   return 0;
}

So is there any way to read from a file and show the output in a console until another input from keyboard is given. Thanks in advance


Solution

  • You either don't mess with stdin to use system("pause") or restore it after use.

    Method 1: Don't mess with stdin

    #include<iostream>
    #include<stdio.h>
    #include<cstdio>
    #include <fstream> // Include this
    #pragma warning(disable:4996)
    using namespace std;
    int main()
    {
        std::ifstream fin("input.txt");  // Open like this
        int n;
        fin >> n;  // cin -> fin
        cout << n << endl;
        system("pause");
       return 0;
    }
    

    Using separate stream for reading file keeps console reading isolated.

    Method 2: Restore stdin

    #include <io.h>  
    #include <stdlib.h>  
    #include <stdio.h>  
    #include <iostream>
    
    using std::cin;
    using std::cout;
    
    int main( void )  
    {  
       int old;  
       FILE *DataFile;  
    
       old = _dup( 0 );   // "old" now refers to "stdin"   
                          // Note:  file descriptor 0 == "stdin"   
       if( old == -1 )  
       {  
          perror( "_dup( 1 ) failure" );  
          exit( 1 );  
       }  
    
       if( fopen_s( &DataFile, "input.txt", "r" ) != 0 )  
       {  
          puts( "Can't open file 'data'\n" );  
          exit( 1 );  
       }  
    
       // stdin now refers to file "data"   
       if( -1 == _dup2( _fileno( DataFile ), 0 ) )  
       {  
          perror( "Can't _dup2 stdin" );  
          exit( 1 );  
       }  
       int n;
       cin >> n;
       cout << n << std::endl;
    
       _flushall();  
       fclose( DataFile );  
    
       // Restore original stdin 
       _dup2( old, 0 );  
       _flushall();  
       system( "pause" );  
    }
    

    Here you restore original stdin so that console input can be used by the system("pause"). Breaking this to 2 separate functions override_stdin and restore_stdin can be more manageable.

    Method 3: Don't use system("pause")

    You can (optionally compile your test program at console using cl command line compilation tool provided by MSVC and) run the program on command line so that output is not missed when the program exits. Or you can search for some IDE options which keep the console for monitoring the output or you can put a breakpoint on the last line. (May be return 0) which may have its own consequences/issues.