1

I'm trying to put another statement to end the while-loop with logical AND:

while ( (character != '\n') && ( i < 10 ) )

...the extra +10:th letters does not get stored in the array. But I can still type in input until pressing ENTER / '\n' .

What am I doing wrong? What happens with the 'extra input'?

This is the code:

char character;
char buffer[81];
int i = 0;

do
{
    character = getchar();
    buffer[i] = character;
    ++i;
} while ( (character != '\n') && (i < 10) );

buffer[i-1] = '\0';
klutt
  • 30,332
  • 17
  • 55
  • 95
ketogo
  • 13
  • 2
  • 3
    You are changing the 10th character to `\0` in line `buffer[i-1] = '\0'`. You meant `buffer[i]` perhaps. When the loop stops, i becomes 10 and you are setting `\0` to `buffer[9]`. – kuro Sep 23 '19 at 12:34
  • 2
    You need to check that i < sizeof(buffer) before you use it to reference [i]. – SPlatten Sep 23 '19 at 12:37
  • @SPlatten That's not needed since the loop stops when i is 10 and the buffers size is 81. – klutt Sep 23 '19 at 13:14
  • @kuro Ah whups. 10 was a "test limit" but same rule applies. Thanks! I'll skip the `do`- loop so `\n`never gets included. – ketogo Sep 23 '19 at 13:52
  • @Splatten Thank you! `sizeof()` is just what I needed. :D – ketogo Sep 23 '19 at 13:53
  • @klutt, it is needed because its a do { } while loop and the test for i is not until after it has been referenced. – SPlatten Sep 24 '19 at 06:01
  • 1
    @SPlatten The above code has zero chance of reading outside the buffer. – klutt Sep 24 '19 at 06:27

2 Answers2

7

The function getchar does not read directly from the keyboard. It reads from stdin. And in most cases what you have written on the keyboard will not end up in stdin until you press enter. This behavior is outside your control and is determined by the terminal you are using.

So your code basically works, except that you should change buffer[i-1] to buffer[i]. If you want to detect keypresses directly, then you will need different methods. There are no good functions in the standard library to do this, but here is an answer that gives you two options. https://stackoverflow.com/a/20349652/6699433

klutt
  • 30,332
  • 17
  • 55
  • 95
  • Yes ok! don't really need it, but I was scared they ended up in some infinite loop/stack/array. 10 was a "test limit", but same rule apply. Thanks a lot! :D – ketogo Sep 23 '19 at 13:35
2

When the do-while loop stops, i becomes 10 in your case. Let's say your input was 0123456789. The input does not contain \n so buffer[9] becomes '9'. Now, after that you are assigning buffer[i - 1] to \0 and buffer[9] becomes \0.

You want buffer[i] = '\0'. Also, do not forget to check that i does not cross the buffer size.

kuro
  • 3,214
  • 3
  • 15
  • 31
  • Ah yes, I see! If I end with *enter* `\n` will be included and if I "extend" the limit <10 it won't be! Maybe I should just skip starting with a `do` loop . – ketogo Sep 23 '19 at 13:44