system(“pause”)不适用于freopen

时间:2011-10-27 16:36:55

标签: c++ console system console-application freopen

见评论见下文。

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;
}

如何让它发挥作用?

3 个答案:

答案 0 :(得分:4)

解决方案1:使用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,请不要忘记添加有关代码正在执行的操作的注释以及原因:)

答案 1 :(得分:1)

使用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技巧)

答案 2 :(得分:0)

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