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