gpt4 book ai didi

c - 我如何在控制台上处理 c 中的箭头键?

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:10 24 4
gpt4 key购买 nike

在处理控制台编辑或删除某些字符时,如何处理c语言中的箭头键。

例如“|”是光标:

>>> hello world|
//after i click on left arrow three times
>>> hello wo|rld
//then i can remove the char "o" or insert new chars

我可以使用此代码获取箭头按钮的 ascii:

#include <stdio.h>
#include <conio.h>
main()
{
int w;
while(1==1)
{
int w = getch();
printf("%d",w);
}
getch();
}

但我不知道下一步是什么?

最佳答案

除特殊情况外,不需要自己写。如果——最后——你只想阅读一行,库和控制台会为用户提供行编辑功能。您需要做的就是接受文本行。

但这确实需要内存管理。在 C 语言中,从堆中分配的一 block 内存必须返回到堆中——恰好一次!拥有单一所有权的概念并了解所有权何时来回传递是很有用的。一些函数将分配一个 block 并将其所有权转移给调用者。调用者必须在使用完 block 后释放 block (或传递所有权)。没有关于所有者是谁的簿记;这只是约定和文档。

顺便说一句,虽然 C 和 C++ 都给了你足够的绳索来吊死自己,但 C++ 可能是一种更好的通用编程语言,因为使用 C 更容易搬起石头砸自己的脚。

getline 函数

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

If *lineptr is set to NULL and *n is set 0 before the call, then getline() will allocate a buffer for storing the line. This buffer should be freed by the user program even if getline() failed.

Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc()-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(), updating *lineptr and *n as necessary.

In either case, on a successful call, *lineptr and *n will be updated reflect the buffer address and allocated size respectively.

http://man7.org/linux/man-pages/man3/getdelim.3.html

因此在这种情况下,调用者将一个缓冲区的所有权转移给函数,而函数又将相同或另一个缓冲区的所有权转移回来。 (realloc() 是一样的。)

char *line = NULL;
size_t len = 0;
ssize_t read;

read = getline(&line, &len, stdin));
if (read != -1) {
// use line in this block
}
free(line); // don't use line after this point

参见 http://man7.org/linux/man-pages/man3/getdelim.3.html有关更长的示例,包括调用 getline() 逐行获取。

关于c - 我如何在控制台上处理 c 中的箭头键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42609534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com