user5693629
user5693629

Reputation:

How can i handle arrow keys in c on console?

How can i handle arrow keys in c language when i dealing with console to edit or delete some characters.

Example the "|" is the cursor:

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

i can get the ascii of the arrow button using this code:

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

but i have no idea what's Next?

Upvotes: 2

Views: 1973

Answers (1)

Tom Blodget
Tom Blodget

Reputation: 20802

Except in special cases, you don't need to write that yourself. If—in the end—you just want to read a line, the libraries and consoles provide line editing features to the user. All you need to do is take in the line of text.

This does require memory management, though. In C, a block of memory assigned from the heap must be returned to the heap—exactly once! It is useful to have the concept of single ownership and understand when ownership is passed back and forth. Some functions will allocate a block and transfer ownership of it to the caller. The caller must free the block when done with it (or pass ownership along). There is no bookkeeping on who the owner is; It is just convention and documentation.

As an aside, although both C and C++ give you enough rope to hang yourself, C++ might be a better language to learn for general programming because with C it is much easier to shoot yourself in the foot.

The getline function

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

So in this case, the caller transfers ownership of one buffer to the function and the function transfers back ownership of the same or another buffer. (realloc() is the same.)

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

See http://man7.org/linux/man-pages/man3/getdelim.3.html for a longer example that includes calling getline() to get line after line.

Upvotes: 1

Related Questions