如何使用C在控制台中以彩色打印出被阻止的客户端

ee7vknir  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(109)

我试图打印出不同颜色的所有客户端.那些没有状态“阻止”在正常的白色颜色,和那些谁有状态“阻止”应该在控制台打印出红色.然而,我有一些格式,像'-'他们破折号,我不能来他们,这意味着我想打印出被阻止的客户端,从单词'BLOCKED'到最后一个em虚线,而不是像现在这样的'Date of reg:'。

BLOCKED
         Client ID: 05300
—————————————————————————————————————
Name: ABC
—————————————————————————————————————
Last: DEF
—————————————————————————————————————
Date of reg: 22-12-2023 18:46:13   <-- this is where the color red ends
————————————————————————————————————  <-- but I want it to end here

//And this client is printed out in normal white color since he does not have status 'blocked'
        Client ID: 05796
—————————————————————————————————————
Name: ERT
—————————————————————————————————————
Last: TYU
—————————————————————————————————————
Date of reg: 22-12-2023 18:49:22
—————————————————————————————————————

字符串
我将输入的数据保存到这样的文件中:

fprintf(file, "\n        Client ID: %05d\n", rand() % 10000);
fprintf(file, "—————————————————————————————————————\n");
fprintf(file, "Name: %s\n", name);
fprintf(file, "—————————————————————————————————————\n");
fprintf(file, "Last: %s\n", last);
fprintf(file, "—————————————————————————————————————\n");
fprintf(file, "Date of reg: %s\n", formatted_date);
fprintf(file, "—————————————————————————————————————\n");


然后我从中读到:

char line[100];
    bool blocked= false;
    rewind(file);
     
    printf("\nPRINTING OUT ALL CLIENTS:\n\n");
    while(fgets(line, sizeof(line), file))
    {
        if (strstr(line, "           BLOCKED") != NULL)
            blocked = true;

        
        if (blocked)
        {
            SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_INTENSITY);
            printf("%s", line);
        }
        else
        {
            SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | 
            FOREGROUND_INTENSITY);
            printf("%s", line);
        }

        if (strstr(line, "Date of reg:") != NULL)  //here is the problem
        {  
            blocked= false;        
        } 
        /* if(strstr(line, "—————————————————————————————————————" != NULL)
               blocked = false; */  this does not help
    }
}


那么,我如何打印出被阻止的客户端,直到最后一个红色的破折号?

8nuwlpux

8nuwlpux1#

当你到达Date of reg:行的时候设置一个变量来表示你已经到达了客户端的末尾。然后在打印一个分隔线之后检查这个。

while(fgets(line, sizeof(line), file))
    {
        if (strstr(line, "           BLOCKED") != NULL) {
            blocked = true;

        SetConsoleTextAttribute(hConsole, FOREGROUND_RED | (blocked ? 0 : FOREGROUND_GREEN) | FOREGROUND_INTENSITY);
        printf("%s", line);
 
        if (strstr(line, "Date of reg:") != NULL)
        {  
            end_of_client = true;        
        } 

        if(end_of_client && strstr(line, "—————————————————————————————————————" != NULL) {
            blocked = false;
            end_of_client = false;
        }

    }

字符串

相关问题