【问题标题】:Why printf not giving output in a windows form C++ application为什么 printf 不在 Windows 窗体 C++ 应用程序中提供输出
【发布时间】:2015-07-03 20:18:42
【问题描述】:

我在 MS VS 2010 中创建了一个简单的 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

出了什么问题??

【问题讨论】:

  • 因为这样的应用程序没有分配控制台。谷歌 Win32“AllocConsole”函数了解更多信息。
  • @Christian.K 谢谢,你能提供一个示例代码吗?我用谷歌搜索,但看起来它们用于非常复杂的代码,我无法理解。
  • That,例如,看起来不是很复杂...
  • @namezero 我使用了 AllocConsole,但新的错误开始出现,请看我修改代码。

标签: winforms visual-studio c++-cli


【解决方案1】:

它不会显示任何输出,因为 WinForm 没有附加控制台。现在,如果您真的想使用控制台

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

参考AllocConsole()

【讨论】:

  • 我建议检查 AllocConsole 的返回值,如果失败,打印一个混乱 - 哦对了。呃,抛出异常?
  • @KABoissonneault 正如你所建议的那样修改以检查返回值。
  • @deeiip 我仍然收到编译错误,请查看我上面的修改代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多