Search code examples
cinputformatfgetsgetline

fgets to include text after newline


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.


Solution

  • 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.