在Visual Studio中使用freopen()时,c ++系统(“暂停”)不起作用

时间:2018-03-12 06:31:34

标签: c++ visual-c++ freopen

我试图从vs17中的文件中读取。但这里系统(“暂停”)不起作用。这里的控制台窗口弹出并消失。 input.txt文件只包含一个整数。

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

有没有办法从文件中读取并在控制台中显示输出,直到给出键盘的另一个输入。提前致谢

2 个答案:

答案 0 :(得分:5)

您要么stdin要使用system("pause"),要么在使用后将其恢复。

方法1:不要混淆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;
}

使用单独的流来读取文件会使控制台读取隔离。

方法2:恢复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" );  
}

您可以在此恢复原始stdin,以便system("pause")可以使用控制台输入。将此细分为2个单独的函数override_stdinrestore_stdin可以更易于管理。

方法3:不要使用system("pause")

您可以(可选择使用MSVC提供的cl命令行编译工具在控制台编译测试程序,并且)在命令行上运行程序,以便在程序退出时不会错过输出。或者,您可以搜索某些IDE选项,这些选项可以使控制台监视输出,也可以在最后一行放置断点。 (可能是return 0)可能有其自身的后果/问题。

答案 1 :(得分:-1)

有关system("pause");

的信息

关于system("Pause")及其使用:我不建议在任何设计用于移植或分发的代码库中使用它,原因如下:Why is it wrong!

现在,如果您正在使用它来进行自己的快速肮脏的黑客攻击,以保持Windows控制台打开,只是为了测试小功能或类很好,但是这里有一个替代方案,可以做同样的事情,符合标准以及便携式的。

#include <iostream>
#include <string>

int main() {        
    [code...]

    std::cout << "\nPress any key to quit.\n";
    std::cin.get(); // better than declaring a char.
    return 0;
}

有关freopen()

的信息

要注意的另一件事是你在文本文件上调用freopen()但是在完成文件后你永远不会有任何关闭文件的调用;我不知道freopen()是否会自动为您执行此操作,但如果它没有,那么您应该在退出程序之前以及从中提取所有需要的信息后关闭文件句柄。

以下是相关问答stack: freopen()

有关freopen()的更多信息,这里有一个优秀的资源网页:C: <cstdio> - freopen()&amp; C++: <cstdio> - std::freopen()

我尝试运行您的代码。

现在我能够测试你的程序了。如果您使用Visual Studio并在调试模式下从调试器运行应用程序,它将在完成后自动关闭应用程序。您可以在没有调试器(ctrl + F5)的情况下运行它,也可以从生成的可执行文件的路径从IDE外部的控制台或终端运行它,程序将以您期望的方式运行。