Hello, I need to do a string input function, the string is entered until the user presses ENTER. Here is the actual code itself:

char* GetLine() { char* line = NULL; char ch; int i = 0; while(true){ ch = getch(); //Считываем, но не выводим символ switch(ch) { case '\r': line = (char*)realloc(line, (i + 1) * sizeof(char)); line[i++] = '\0'; //Признак конца строки return line; case '\b': printf("\b \b"); //Удаляем символ в консоле if (i > 0) i--; break; default: putchar(ch); line = (char*)realloc(line, (i + 1) * sizeof(char)); line[i++] = ch; } } } 

What is the actual problem, I need that when I press the individual keys (F1-F12, Esc, numbers on the numpade, etc.) they are not displayed in the console. I know that you can use a switch to scan all keys with a scancode, but it seems to me that the solution should be easier.

  • If getch returns 0, ignore the next return. With memory allocation, your approach is incorrect - to allocate for each character. Select a piece, if necessary - double, it will be much more efficient. And the last - the task is worth it - exactly getch() ? Do not just read, dynamically increasing the size of the buffer, namely this function? because all the same is done much easier through getchar for example, and without these perversions ... - Harry
  • I did input with getchar () (everything worked fine), but I put the lecturer at a dead end, they say, I enter more than one character in the getchar () function, but I don’t know about the input buffer yet. How does the buffer itself actually increase? - ReCursia

1 answer 1

In the comment reply - there is not enough space ...

In this case, you absolutely shouldn't be bothered by the input buffer, since you still end your input by pressing Enter. How the compiler and the operating system handle it are their problems. Here is the code -

 #include <stdlib.h> #include <stdio.h> #include <string.h> char * read() { size_t size = 8; char * buf = (char*)malloc(size*sizeof(char)); size_t count = 0; for(int c = ' ' /*Неважно что, лишь бы не нуль */;c;) { c = getchar(); if (c == EOF || c == '\n') c = '\0'; if (count == size) { buf = (char*)realloc(buf,size *= 2); } buf[count++] = c; } return buf; } int main() { char * s = read(); printf("You wrote: [%s]\n",s); free(s); } 

Enter at least a megabyte string, if only realloc worked. The lecture here, I believe, is fundamentally wrong.

In the case of getch() any function keys give 2 codes in a row, the first one is 0 or 0xE0. If you see such a code, read the second code and ignore both of them. Only here about, say, Russian at the same time will have to forget ...