系统( "pause" ) 不适用于 freopen

system("pause") won't work with freopen

本文关键字:适用于 freopen 不适用 pause 系统      更新时间:2023-10-16

见下面的评论

int main(){
    //freopen("input.txt","r",stdin);//if I uncomment this line the console will appear and disappear immediately
    int x;
    cin>>x;
    cout<<x<<endl;
    system("pause");
    return 0;
}

如何让它工作?

方案一:用cin.ignore代替system:

...
cout<<x<<endl;
cin.ignore(1, 'n'); // eats the enter key pressed after the number input
cin.ignore(1, 'n'); // now waits for another enter key
...

解决方案2:如果你使用的是MS Visual Studio,按Ctrl+F5

解决方案3:重新打开con(只适用于Windows,似乎你的情况)

...
cout<<x<<endl;
freopen("con","r",stdin);
system("pause");
...

如果您使用解决方案3,不要忘记添加注释,说明代码正在做什么以及为什么:)

使用std::ifstream代替重定向stdin:

#include <fstream>
#include <iostream>
int main()
{
    std::ifstream fin("input.txt");
    if (fin)
    {
        fin >> x;
        std::cout  << x << std::endl;
    }
    else
    {
        std::cerr << "Couldn't open input file!" << std::endl;
    }
    std::cin.ignore(1, 'n'); // waits the user to hit the enter key
}

(从anatolyg的回答中借用了cin.ignore的技巧)

使用freopen更改程序的标准输入。您启动的任何程序都继承您的程序的标准输入,包括pause程序。pause程序从input.txt读取一些输入,然后终止