0

I want to make an array of characters and store the whole input in it(even if the input contains "\n" at some point. When i use:

char vhod[50];

fgets(vhod, sizeof(vhod), stdin);

it stores the input UNTIL the first newline. How to get the whole text in this array(including the text after the new line). Example: if my text is:

Hello I need new keyboard.
This is not good.

my array will only contain "Hello I need new keyboard.". I want to be able to read everything till the end of input a < input-1 I cannot use FILE open/close/read functions since it is input from keyboard.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Denko Mancheski
  • 2,709
  • 2
  • 18
  • 26
  • 2
    What makes you think you can't use `read()` when the input is from the keyboard? – Barmar Apr 09 '15 at 01:02
  • You don't have to call `open()`, since standard input is already open. – Barmar Apr 09 '15 at 01:02
  • 1
    If you're using the standard I/O library, then `fread()` is the obvious choice, rather than the file descriptor function `read()`. Of course, you'll need to be careful not to overflow the buffer; 50 characters is rather small. Or you can use `fgets()` incrementally; or you could consider POSIX function [`getdelim()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getdelim.html) (a near relative of `getline()`), passing a character such as `'\0'` as the 'line delimiter' so it reads everything up to a null byte or EOF. – Jonathan Leffler Apr 09 '15 at 01:06

1 Answers1

0

While fgets() is designed to read up to a '\n' character or the specified number of bytes, you can use fread()1 instead, like this

size_t count = fread(vhod, 1, sizeof(vhod), stdin);

and count will contain the number of items read, which in this case is the same as the number of bytes since you are providing size 1 i.e. sizeof(char).

Note however that you must be very careful to add a terminating '\0' if you are going to use any function that assumes a terminating '\0'.


1Read the manual for more information.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97