0

The problem is that when i typed

printf("\033[1;32mHello World\033[0m");

it prints something like this

[1;32mHello World[0m 

in the console. My code is

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

int main(){

    printf("\033[1;32mHello World\033[0m");

    _getch();
    return 0;
}

it displays:

a box with a question mark inside->[1;32mHello World[0m

but should be a color green text color Hello World.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • 9
    That is because the terminal you are using doesn't support VT100 color coding. – Havenard Jan 02 '19 at 21:53
  • okay but why does when i set a header file and type the same thing in the header file it works im so confused right now – Nikki Gonzales Jan 02 '19 at 21:56
  • 1
    What do you mean by "set a header file"? – tadman Jan 02 '19 at 22:03
  • By the way this code, minus the `_getch()` and `#include `, which are platform specific, works for me. Make sure you're running this in an ANSI compatible terminal. Your compiler's output window is probably not interpreting [ANSI characters properly](https://en.wikipedia.org/wiki/ANSI_escape_code), and the shell you're in might not be set to have colours enabled. – tadman Jan 02 '19 at 22:05
  • Maybe `cat` on Windows does the color processing because it knows the terminal wont do it. – Havenard Jan 02 '19 at 22:18
  • "set a header file" i mean i also include another header file in my main class and typed the code in my created function and just called my function into the main class and for some reason it worked ...... example: #include "Header Files/Hello.h"<-----inside this .h file there a function where i print the color coded hello world – Nikki Gonzales Jan 02 '19 at 23:25
  • and by the way thanks for all your help – Nikki Gonzales Jan 02 '19 at 23:31
  • `main()` is not a class, it is a specific *function* of type `int` mandated by the C standard for hosted environments and may be *implementation defined* for freestanding (embedded) systems. What version of windows are you using? Is the terminal used after you include the header that produces the green text the same one that fails without the header (which makes no sense whatsoever). Let us know. Testing at the shell on Linux, `printf "\033[1;32mHello World\n\033[0m"` works just fine. – David C. Rankin Jan 03 '19 at 02:39

1 Answers1

0

Maybe in this way:

HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwMode = 0;
GetConsoleMode(hStdout, &dwMode);
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hStdout, dwMode);
printf("\033[1;32mHello World\033[0m");

You need to initialize the appropriate mode Windows console.

stansy
  • 135
  • 1
  • 10