Изменить цвет выводимого текста - C (СИ)
Формулировка задачи:
#include<conio.h>
main()
{
textcolor(RED);
cprintf("Hello!");
return 0;
}#include <windows.h> //header file for windows
#include <stdio.h> //C standard library
void SetColor(int ForgC);
int main()
{
SetColor(34);
printf("test clour");
return 0;
}
void SetColor(int ForgC)
{
WORD wColor;
//We will need this handle to get the current background attribute
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
//We use csbi for the wAttributes word.
if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
//Mask out all but the background attribute, and add in the forgournd color
wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
SetConsoleTextAttribute(hStdOut, wColor);
}
return;
}Решение задачи: «Изменить цвет выводимого текста»
[#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <math.h>
void SetColor(int ForgC);
int main()
{
int s;
float x;
printf("\n \t 1)cos(x*x) \n \t 2)4*x*x+7 \n \t 3)sqrt(x*x+x+4)\n");
SetColor(35);
printf("Choose somethin to count the x: ");
scanf("%i", &s);
switch((s>=1 && s<=3)?s:0)
{
case 1 :
printf("X is: ");
scanf("%f", &x);
x = cos(x*x);
printf("The result of x is %.02f", x);
getchar();
break;
case 2 :
printf("X is: ");
scanf("%f", &x);
x = (4*x*x+7);
printf("The result of x is %.02f", x);
getchar();
break;
}
return 0;
void SetColor(int ForgC)
{
WORD wColor;
//We will need this handle to get the current background attribute
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
//We use csbi for the wAttributes word.
if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
//Mask out all but the background attribute, and add in the forgournd color
wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
SetConsoleTextAttribute(hStdOut, wColor);
}
return;
}
}
Объяснение кода листинга программы
[1] Включаются необходимые заголовочные файлы [2] Определяется функция SetColor, которая меняет цвет вывода текста [3] В функции main происходит вывод списка вариантов для выбора [4] Вызывается функция SetColor с аргументом 35, который соответствует цвету фона 35 (предположительно синий) [5] Происходит запрос на ввод числа от пользователя с помощью функции scanf [6] Выполняется операция switch в зависимости от выбранного пользователем числа [7] При выборе варианта 1 происходит вывод приглашения для ввода числа и результата вычисления функции cos(xx) [8] При выборе варианта 2 происходит вывод приглашения для ввода числа и результата вычисления функции 4x*x+7 [9] В функции SetColor происходит получение текущего цвета фона с помощью функции GetStdHandle и GetConsoleScreenBufferInfo [10] Происходит установка цвета текста с помощью функции SetConsoleTextAttribute [11] Возвращается управление в основную программу [12] Завершается функция main [13] Завершается программа