【问题标题】:How to properly use setvbuf in C?如何在 C 中正确使用 setvbuf?
【发布时间】:2021-07-16 19:02:48
【问题描述】:

我想使用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';

        //...
    }
}

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

【问题讨论】:

  • 参数被忽略,但您仍然需要传递它们。

标签: c io buffering


【解决方案1】:

使用fake参数:

setvbuf(stdin, NULL, _IONBF, 0);

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

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

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

【讨论】:

  • 感谢您的帮助,但由于某种原因,我仍然必须按 Enter 才能将字符发送到标准输入。如果我没记错的话,无缓冲输入意味着当我按下一个键时输入被正确发送到程序,对吧?还是有其他问题?
  • @MatthewSchell,那很好,但不,您仍然必须按 Enter。
  • @MatthewSchell,问题在终端中,而不是在缓冲中,你需要使用别的东西,如果你在 linux 机器上我会建议 ncurses。
  • 类似getch()?
  • @MatthewSchell,是的,那是来自 Windows conio.h 不是吗?
猜你喜欢
  • 2020-08-26
  • 2013-08-26
  • 1970-01-01
  • 2015-07-12
  • 2013-04-10
  • 1970-01-01
相关资源
最近更新 更多