3

我试图从 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;
}

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

4

2 回答 2

5

您要么不乱用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_stdin,并且restore_stdin可以更易于管理。

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

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

于 2018-03-12T07:06:13.913 回答
-1

相关信息system("pause");

至于system("Pause")它的用途:我不建议在任何设计用于移植或分发的代码库中使用它,原因如下:为什么它错了!.

现在,如果您将它用于您自己的快速肮脏黑客攻击以保持 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()会自动为您执行此操作,但如果没有,那么您应该在退出程序之前以及从中提取所有需要的信息之后关闭文件句柄。

这是一个相关的 Q/A stack: freopen()

有关freopen()此处的更多信息,请参阅一个出色的资源网页:C: <cstdio> - freopen()&C++: <cstdio> - std::freopen()


我尝试运行您的代码。

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

于 2018-03-12T06:43:36.040 回答