2

I'm trying to redirect traces on an output console on Windows Visual 2012, Linker/Subsystem = Windows (/SUBSYSTEM:WINDOWS), using a classical RedirectIOToConsole function.

Performing std::endl before AllocConsole seems to causes problems to display traces.

Below is my test:

#include <windows.h>     
#include <stdio.h>
#include <iostream>  
void RedirectIOToConsole()
{
  FILE *conin, *conout; 
  AllocConsole();
  freopen_s(&conin, "conin$", "r", stdin);
  freopen_s(&conout, "conout$", "w", stdout);
  freopen_s(&conout, "conout$", "w", stderr);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
  // std::cout << "My Trace 1";              // Uncomment this line for Test 1
  // std::cout << "My Trace 1" << std::endl; // Uncomment this line for Test 2
  RedirectIOToConsole();
  printf( "redirected console\n");
  std::cout << "My Trace 2" << std::endl;
  ch = getchar();
  return 0;
}
  • Run it as it is - output in Console window:

redirected console

My Trace 2 -> OK

  • Uncomment line for test 1 - output in Console window:

redirected console

My Trace 2 -> OK

  • Uncomment line for test 2 - output in Console window:

redirected console -> NOK

4

1 回答 1

11

在你打电话之前,RedirectIOToConsole()没有什么cout可以输出的。由于cout是缓冲的,因此输出将存储在缓冲区中,直到flush执行 a 为止。endl包含一个flush.

当您尝试在没有可用控制台的情况下刷新输出时,coutbadbitiostate.

然后,当您执行下一步时cout << "My Trace 2" << endl;,输出不会继续进行,因为在实际将数据写入输出文件(stdout)之前,cout检查iostate并说“哦,这不好,我们已经badbit设置”并退出而不尝试写入.

从理论上讲,您可以通过调用来解决此问题cout.clear();,但我建议cout在分配控制台之前不要调用它是一个更好的计划 - 在您有东西要输出之前输出东西是没有用的。

于 2013-09-20T10:55:10.167 回答