mos*_*raf 3 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;
}
Run Code Online (Sandbox Code Playgroud)
那么有没有办法从文件中读取并在控制台中显示输出,直到给出键盘的另一个输入.提前致谢
您要么在使用后不要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;
}
Run Code Online (Sandbox Code Playgroud)
使用单独的流读取文件使控制台读取隔离.
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" );
}
Run Code Online (Sandbox Code Playgroud)
在这里你恢复原始,stdin以便控制台输入可以被使用system("pause").将其分解为2个独立的功能override_stdin,restore_stdin可以更易于管理.
system("pause")您可以(可选地使用clMSVC提供的命令行编译工具在控制台上编译测试程序)并在命令行上运行程序,以便在程序退出时不会错过输出.或者,您可以搜索某些IDE选项,这些选项可以使控制台监视输出,也可以在最后一行放置断点.(可能return 0)可能有其自身的后果/问题.
| 归档时间: |
|
| 查看次数: |
1000 次 |
| 最近记录: |