2015-07-03 38 views
0

的printf不給輸出我創建了一個簡單的Windows形成MS VS 2010應用程序C++項目,然後我打算打印到控制檯:爲什麼在Windows窗體中的C++應用程序

// FtoC.cpp : main project file. 

#include "stdafx.h" 
#include "Form1.h" 
#include <stdio.h> 
#include<conio.h> 

using namespace FtoC; 

[STAThreadAttribute] 
int main(array<System::String ^> ^args) 
{ 
    printf (" printing to console"); 


    // Enabling Windows XP visual effects before any controls are created 
    //Application::EnableVisualStyles(); 
    //Application::SetCompatibleTextRenderingDefault(false); 

    // Create the main window and run it 
    //Application::Run(gcnew Form1()); 


    getch(); 
    return 0; 
} 

正如你可以看到我有評論除了我的printf語句外。

它編譯沒有任何錯誤,但沒有輸出。爲什麼是這樣?

我修改了代碼,如下圖所示:

#include "stdafx.h" 
#include <Wincon.h> 
#include "Form1.h" 

#include <stdio.h> 
#include<conio.h> 


using namespace FtoC; 

[STAThreadAttribute] 
int main(array<System::String ^> ^args) 
    { 

    BOOL chk = AllocConsole(); 
if(chk) 
{ 
    freopen("CONOUT$", "w", stdout); 
    printf (" printing to console"); 
} 
    else 

{ 
    throw new SomeException(); 
} 
    getch(); 
    return 0; 
} 

但現在我得到很多在WINGDI.H文件中的錯誤,如:

Error 270 error C1003: error count exceeds 100; stopping compilation C:\Program Files\Microsoft SDKs\Windows\v7.0A\include\wingdi.h 750 1 FtoC 


Error 159 error C2065: 'MAX_PATH' : undeclared identifier C:\Program Files\Microsoft SDKs\Windows\v7.0A\include\wingdi.h 683 1 FtoC 

出了什麼問題?

+1

因爲這樣的應用程序沒有分配一個控制檯。 Google Win32的「AllocConsole」函數獲取更多信息。 –

+0

@ Christian.K謝謝,請給出一個示例代碼?我google搜索,但它看起來像他們用於一個非常複雜的代碼,我無法理解。例如, –

+1

[That](http://stackoverflow.com/a/15547699/21567)看起來不太複雜... –

回答

2

它不會顯示任何輸出,因爲WinForm沒有連接到它們的控制檯。現在,如果你真的想使用控制檯

BOOL chk = AllocConsole(); 
if(chk) 
{ 
    freopen("CONOUT$", "w", stdout); 
    printf (" printing to console"); 
} 
else 
{ 
    throw new SomeException(); 
} 

參考AllocConsole()

+0

我建議檢查AllocConsole的返回值,如果失敗,打印一個爛攤子 - 哦,哦。呃,拋出異常? – KABoissonneault

+0

@KABoissonneault根據您的建議修改爲檢查返回值。 – deeiip

+0

@deeiip我仍然收到編譯錯誤,請看看我上面修改過的代碼。 –

相關問題