c - 双缓冲和 printf

标签 c printf buffer

我在让其他基本函数使用双缓冲区时遇到问题。

例如,在下面的代码中,它运行,我可以按向下或向上移动光标,当我按 Enter 时,我应该得到一个 printf 说要么创建一个新字符,加载,要么再见。

它出现一瞬间,然后立即消失。在这些情况下,rewind(stdin) 和 getchar();解决了这个问题,但对于这段代码,似乎没有任何作用。

请帮忙。

#define _CRT_SECURE_NO_WARNINGS
#include "conioex.h"
#include "DblBuffer.h"

enum // 
{
    NEW_GAME = 20,
    LOAD,
    EXIT,
    MAX_NUM
};

void main (void)
{
    DblBuffer db;
    int Cursor_X, Cursor_Y; // cursorlocation
    bool Key_flag = false;  // pressandtrue
    int type = NEW_GAME;    // type
    Cursor_X = 20;
    Cursor_Y = 1;
    int flag = 1;
    while (flag)
    {
        for (int i = 1; i <= 3; i++)
        {
            db.setCursorPos(20,i);
            db.write(" ");
        }
        db.setCursorPos(25,1);
        db.write("New Game\n");
        db.setCursorPos(25,2);
        db.write("Load\n");
        db.setCursorPos(25,3);
        db.write("Exit\n");

        if (inport(PK_DOWN))
        {
            if (Key_flag == false)
            {
                Cursor_Y = Cursor_Y + 1;
                type = type + 1;
                Key_flag = true;
            }
        }
        else if (inport(PK_UP))
        {
            if (Key_flag == false)
            {
                Cursor_Y = Cursor_Y - 1;
                type = type - 1;
                Key_flag = true;
            }
        }
        else if (inport(PK_ENTER))
        {
            flag = 0;
            break;
        }
        else
        {
            Key_flag = false;
        }

        if (Cursor_Y < 1)
        {
            Cursor_Y = 1;
        }
        if (Cursor_Y > 3)
        {
            Cursor_Y = 3;
        }

        if (type < NEW_GAME)
        {
            type = NEW_GAME;
        }
        if (type >= MAX_NUM)
        {
            type = MAX_NUM - 1;
        }

        db.setCursorPos(Cursor_X, Cursor_Y);
        db.write("→");
        db.swap();
    }

    if(type == NEW_GAME)
    {
        printf("making a new game");
    }
    if (type == LOAD)
    {
        printf("will load");
    }
    if (type == EXIT)
    {
        printf("goodbye");
    }

    rewind(stdin);
    getchar();
}

最佳答案

至于你的问题,“然后它立即消失”我认为控制台窗口很快消失?

那是因为程序退出了。

您需要刷新连接到 stdin 的输入缓冲区,以删除您所做的所有按键(通过从 stdin读取),然后调用getchar 额外一次以获得用户想要退出的一种确认。

关于c - 双缓冲和 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53524213/

相关文章:

c++ - 遍历 vector 并将元素复制到 C 数组中

c++ - gdb,连接到使用 gdbserver 启动的正在运行的进程

c - c 中的 fopen 和 fputs

C printf 带有 %lu 的整数产生大数

java printf 格式带有字符串参数的 double

bash - bash 窗口中的水平滚动

Qt - 什么是示例缓冲区?

c - 使用带有信号量和线程的 C 语言进行文件复制,供消费者/生产者使用

c - float 及其对 8 位微 Controller 存储器的影响

javascript - 为什么长度为 3 的字符串的字节长度为 3?