如何在Windows Application中应用printf函数?

下面,我们先看一个最简单的Windows应用程序:

#include <windows.h>int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd ){MessageBox(0, "调用了WinMain函数", "测试:", 0);return 0;} 那么,如何在其中用printf函数呢?试看看下面的程序:#include <windows.h>#include <stdio.h>int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd ){printf("调用了WinMain函数\n");MessageBox(0, "调用了WinMain函数", "测试:", 0);return 0;} 这个程序达不到效果,为什么呢?因为根本就没有那个黑色的控制台,printf函数怎么能起作用呢?我们先来看看下面这个程序:#include <windows.h>#pragma comment( linker, "/subsystem:\&;console\&; /entry:\&;WinMainCRTStartup\&;")int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd ){return 0;} 该程序运行后,能弹出一个黑色的控制台,所以在Windows应用程序中,可以通过下面的方式来使用printf函数:#include <windows.h>#include <stdio.h>#pragma comment( linker, "/subsystem:\&;console\&; /entry:\&;WinMainCRTStartup\&;")int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd ){printf("调用了WinMain函数\n");MessageBox(0, "调用了WinMain函数", "测试:", 0);return 0;}

这样,,就可以了。为什么要在Windows应用程序中使用printf函数呢?便于理解程序和调试呗!

我们看到,在Windows应用程序中,不能直接使用printf, 一般需要加上#pragma那一句,但是,还有没有别的方法来看程序的结果呢?有的,虽然不能直接用printf, 但是可以用fprintf啊,这样,结果就不在控制台上,而是在文件中,同样可以方便地理解和调试程序。不得不说:在这里,printf比fprintf方便多了,也好多了。

既有美妙的风景,也会有称不上景只有风的地方。

如何在Windows Application中应用printf函数?

相关文章:

你感兴趣的文章:

标签云: