2011-10-27 83 views
0

請參閱下面的評論。系統(「暫停」)不能與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; 
} 

如何使它工作?

+5

更重要的是,*你爲什麼要使用'系統( 「暫停」)'*? –

+0

我使用這個功能,因爲我想看到程序輸出。 – SevenDays

+0

閱讀此:http://www.gidnetwork.com/b-61.html和/或此:http://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong –

回答

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:如果您正在使用微軟的Visual Studio中,按Ctrl + F5鍵

解決方案3:重新con(僅在Windows上運行,看來你的情況下)

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

如果您使用的解決方案3,不要忘記上添加註釋什麼代碼做什麼,以及爲什麼:)

+0

解決方案3工作得很好!謝謝!我的程序讀取數字的input.txt文件並生成一些數據。這是爲了學習。 – SevenDays

+0

呵呵,這是一個令人討厭的雜食,但它有*風格* – anatolyg

0

您使用freopen來更改程序的標準輸入。您開始的任何程序都會繼承程序的標準輸入,包括pause程序。 pause程序從input.txt中讀取一些輸入並終止。

+0

我不瞭解如何使其工作。你有答案嗎? – SevenDays

+1

@wsevendays:從命令行運行你的程序。 –

+0

我需要通過雙擊運行程序,並將數據輸出到控制檯。但是我的程序在輸出數據後立即消失。 – SevenDays

1

使用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招)