I have a character string. I need to enter a value from the keyboard that does not exceed 10 characters. When you enter 11 characters, the function that reads these characters from the keyboard should end. How can you organize such input, is there a built-in function, or you just need to count the number of characters entered in the cycle and compare them with the required size? Thank!

  • Why don't you just cut the entered string? What is the problem that the user must enter exactly 10 characters? - Vlad from Moscow Nov.
  • Read the docks, they rulez . True, if you enter a larger number of characters, it will not end, but the line will not get more than the desired one. - PinkTux
  • Is the input string limited to space or only 10 characters? - user227465

1 answer 1

Well, formally, you can do something like this:

int main(int argc, const char * argv[]) { char input[11]; memset(input,0,11); for(int i = 0; i < 10; ++i) { input[i] = getch(); putchar(input[i]); if (input[i] == '\r') { input[i] = 0; break; } } printf("\nInput: [%s]\n",input); } 

But at the same time, the user is deprived of the possibility of correcting his input (for example, using backspace). So think - maybe it makes sense or just read a long line and cut it later, or read no more than 10 characters -

 char input[11]; fgets(input,10,stdin); printf("\nInput: [%s]\n",input); 

(with trimming the last '\ n' for a shorter line, if this is important).

  • he is deprived only in this case. you can make the control switch (ch) ... 8 - backspace, i = i? i -: 0 ... or in another way - J. Doe
  • @ J.Doe If a person asks how to do this at all - he is unlikely to write such line editing - especially since you need to display the corrections on the screen accordingly ... - Harry