c++ - 在 Visual Studio C++ 系统 ("pause"中使用 freopen() 时)不工作

标签 c++ visual-c++ freopen

我试图从 vs17 中的文件中读取。但是这里 system("pause") 不起作用。此处的控制台窗口弹出并消失。 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;
}

那么有什么方法可以从文件中读取并在控制台中显示输出,直到给出来自键盘的另一个输入。提前致谢

最佳答案

你要么不要乱用 stdin 来使用 system("pause") 要么在使用后恢复它。

方法一:不要乱用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;
}

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

方法二:恢复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 可以更易于管理。

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

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

关于c++ - 在 Visual Studio C++ 系统 ("pause"中使用 freopen() 时)不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49229303/

相关文章:

c++ - 条件自动变量

c++ - list::remove_if 等效

c++ - 在 d2i_RSAPrivateKey_fp() 中崩溃

c++ - SDL Console 输出在调试时有效,但在使用 exe 运行时无效

c - 检查C中freopen()的返回值

c - 在循环中重新分配文件指针

c++ - 使用 Mat OpenCV 访问像素

c++ - 显式模板特化不能有存储类 - 成员方法特化

c++ - 我可以使用 Visual C++ 开发跨平台桌面应用程序吗?

c++ - 在 Visual C++ 2010 中执行前先执行 bat 脚本