微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 C 中正确使用 setvbuf?

如何解决如何在 C 中正确使用 setvbuf?

我想使用 setvbuf() 将我的输入流设置为无缓冲,但我真的不知道如何使用它。

我做了一些谷歌搜索,发现当您将流设置为无缓冲时,缓冲区和大小参数将被忽略,如 this article 所述。

这是我的代码

#include "structures.h"
#include "functions.h"

char choice;
int option;

int main(void) {
    while(1) {
        puts("============================================Select an Option============================================");
        puts("1. Create Linked List");
        puts("2. display items");
        puts("3. Add item to the beginning");
        puts("4. Add item to the end");
        puts("5. Add item in the middle");
        puts("6. Delete item from the beginning");
        puts("7. Delete item from the end");
        puts("8. Delete item from the middle");
        puts("9. Exit");
        printf(">>> ");

        setvbuf(stdin,_IONBF);
        choice = getchar();
        cleanStdin();
        option = choice - '0';

        //...
    }
}

文章说它们被忽略了,但我仍然收到关于参数不足的错误,所以我不知道在那里放什么。有人可以帮我吗?

解决方法

使用参数:

setvbuf(stdin,NULL,_IONBF,0);

但是,这将不允许您在不按 Enter 的情况下从终端读取字符,这是终端问题,而不是缓冲问题,因为您需要其他东西。

您可以使用 ncurses,这是建议的路线,但您也可以使用此帖子中接受的答案 What is the equivalent to getch() & getche() in Linux?,它可以让您完全做到这一点。

你可以在这里看到它的工作:https://replit.com/@anastaciu/ConcernedAncientMenu

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。