2016-12-05 103 views
1

在HTML5中,你可以通過做這樣使彩色文本:的XCode WINDOWS.H和顯示彩色文字

.foo 
{ 
    color: rgb(0,0,0); 
} 

我最近開始C++,並想顯示彩色文本給用戶。我GOOGLE了這一點,並用東西想出了這樣的:

http://www.cplusplus.com/forum/beginner/5830/

Duoas'代碼段(如下圖所示)看起來有點意思,我試圖在XCode中運行它。

#include <iostream> 
#include <windows.h> 

int main() 
{ 
    const WORD colors[] = 
     { 
     0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F, 
     0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6 
     }; 

    HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE ); 
    HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    WORD index = 0; 

    // Remember how things were when we started 
    CONSOLE_SCREEN_BUFFER_INFO csbi; 
    GetConsoleScreenBufferInfo(hstdout, &csbi); 

    // Tell the user how to stop 
    SetConsoleTextAttribute(hstdout, 0xEC); 
    std::cout << "Press any key to quit.\n"; 

    // Draw pretty colors until the user presses any key 
    while (WaitForSingleObject(hstdin, 100) == WAIT_TIMEOUT) 
    { 
     SetConsoleTextAttribute(hstdout, colors[ index ]); 
     std::cout << "\t\t\t\t Hello World \t\t\t\t" << std::endl; 
     if (++index > sizeof(colors)/sizeof(colors[0])) 
      index = 0; 
    } 
    FlushConsoleInputBuffer(hstdin); 

    // Keep users happy 
    SetConsoleTextAttribute(hstdout, csbi.wAttributes); 
    return 0; 
} 

但是,我得到的錯誤是

2:21: fatal error: windows.h: No such file or directory 
compilation terminated. 

因此,這裏是我的問題: 有沒有在Xcode中WINDOWS.H替代? 如果不是,您如何向控制檯顯示顏色?

(注:我試圖讓我的Hello World程序顯示的Hello World另一種顏色,而不是黑色)

任何幫助表示讚賞。 謝謝!

編輯: 好吧,多虧了duskwuff的回答,我知道windows.h只能在windows上運行。我有一臺PC,但它沒有運行在我目前使用的編譯器上。我可以使用什麼編譯器來運行代碼示例?

+0

在這裏有一個廁所: http://stackoverflow.com/questions/9158150/colored-output-in-c – carrotcake

+0

好的,這有很大的幫助。但是,我仍然無法運行代碼。儘管感謝您的快速回復! –

回答

0

您嘗試使用的示例代碼與Windows控制檯高度特定,並且在macOS中沒有直接的等效項。

Xcode控制檯不支持顏色。

如果您在macOS終端(不是Xcode控制檯)上運行應用程序,則可以使用use ncurses to display colors。或者,you can use color code escapes directly

+0

感謝您的回覆。現在我意識到示例代碼無法在XCode上運行,我可以在什麼編譯器上運行它?我有一臺PC,但它沒有運行在我使用的編譯器Ubuntu上。 –