C++ - How to write text to the console

Using: printf, fprintf, cout, cerr, fwrite, WriteConsoleA.


  printf("hello - printf\r\n");
  printf("hello - printf %03d\r\n", 42);
  
  fprintf(stdout, "hello - fprintf %03d\n", 42);
  fprintf(stderr, "hello - fprintf %03d\n", 42); // stderr
  
  cout << "hello - cout" << endl;
  cerr << "hello - cerr" << endl; // stderr
  cout << "hello - cout " << std::setw(3) << setfill('0') << 42 << endl;
  
  {
      char message1[] = "hello - cout.write\r\n";
      char message2[] = "hello - cerr.write\r\n";
      cout.write(message1, strlen(message1));
      cerr.write(message2, strlen(message2)); // stderr
  }
  
  {
      char message[] = "hello - fwrite\r\n";
      fwrite(message, 1, strlen(message), stdout);
      fwrite(message, 1, strlen(message), stderr); // stderr
  }
  
  {
      char message[] = "hello - WriteConsoleA\r\n";
      WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), message, strlen(message), NULL, NULL);
      WriteConsoleA(GetStdHandle(STD_ERROR_HANDLE), message, strlen(message), NULL, NULL); // stderr
  }
  
  // via a buffer
  char buffer[64];
  sprintf_s(buffer, "hello - %03d\r\n", 42);
  printf(buffer);
  
  std::ostringstream ss;
  ss << "hello - " << setw(3) << setfill('0') << 42 << endl << flush;
  cout << ss.str();
  
  printf("\r\n");
  

Program output:

  hello - printf
  hello - printf 042
  
  hello - fprintf 042
  hello - fprintf 042
  
  hello - cout
  hello - cerr
  hello - cout 042
  
  hello - cout.write
  hello - cerr.write
  
  hello - fwrite
  hello - fwrite
  
  hello - WriteConsoleA
  hello - WriteConsoleA
  
  hello - 042
  hello - 042
  


Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath