【问题标题】:system("pause") won't work with freopensystem("pause") 不适用于 freopen
【发布时间】:2011-10-27 16:36:54
【问题描述】:

请参阅下面的评论。

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

如何让它发挥作用?

【问题讨论】:

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


【解决方案1】:

解决方案 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,请不要忘记在代码正在做什么以及为什么添加 cmets :)

【讨论】:

  • 解决方案3效果很好!谢谢!我的程序读取 input.txt 文件中的数字并生成一些数据。这是为了学习。
  • 呵呵,这是一个令人讨厌的组合,但它有风格
【解决方案2】:

使用std::ifstream 而不是重定向标准输入:

#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 技巧)

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 我需要双击运行程序,并将数据输出到控制台。但是我的程序在输出数据后立即消失了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多