Hi,im making a console application,i would like certain printf:("") to have different colour than the others,is that possible?

Dani AI

Generated

asked whether individual printf calls can use different color (and font size). was correct that color is doable but not portable across terminals. Two practical approaches follow, plus a note about font size.

Option 1 — ANSI escape sequences (portable where the terminal supports them). Example:

printf("\x1b[31mThis text is red\x1b[0m\n");

The \x1b[31m sets foreground red and \x1b[0m resets attributes. Works on many Unix-like terminals and modern terminals that implement VT sequences. Reference: ANSI escape code.

Option 2 — Native console API for precise control (save current attributes, set new, print, restore). Minimal pattern in C:

#include <windows.h>
#include <stdio.h>

void print_colored(const char *s, WORD color) {
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(h, &csbi);
    WORD orig = csbi.wAttributes;
    SetConsoleTextAttribute(h, color);
    printf("%s", s);
    SetConsoleTextAttribute(h, orig);
}

Save and restore attributes so later output keeps expected colors. See SetConsoleTextAttribute for details.

Font size cannot be changed per-character in a standard console; font settings apply to the console window as a whole (programmatic changes affect the whole console). For per-text styling, a GUI window or a text-rendering library is required. See SetCurrentConsoleFontEx for the console-wide font API.

Recommended Answers

All 2 Replies

Yes, it's possible. No, it's not portable. Yes, you need to say what compiler and OS you're using.

im using microsoft visual 2005 and windows 7

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.