Search code examples
c++ccompilationfgets

Example from "Sams teach yourself C" Uses "fgets" but returns errors


The code included is exactly out of the book example, but it returns errors. Is there something that the book has done incorrectly? I've never used #include <string.h> before, only #include <stdio.h>, but still I'm at a loss of what the three arguments are supposed to be.

#include <stdio.h>
#include <string.h>
int main(void)
{
    char buffer[256];

    printf("Enter your name and press <Enter>:\n");
    fgets(buffer);

     printf("\nYour name has %d characters and spaces!",
         strlen(buffer));
    return 0;
}

The compiler says

Semantic issue with (fgets( buffer ); - Too few arguments to function call, expected 3, have 1

Format string issue (strlen(buffer)); - Format specifies type 'int' but the argument has type 'unsigned long'

Solution

  • fgets() must take three parameters.

    1. The string were to put the read value
    2. The number of bytes to write in this string. But if you the Enter key caracter is found it will stop at this moment.
    3. The stream where to read the data from.

    Here you are only specifying one argument so this is not enough. This is what causes the error. There is a simplified version of fgets that just reads data that is typed by the user and it is called gets().

    gets(buffer);
    

    But this function is unsafe because if the user inputs more bytes than the size of your buffer then you will have a memory overflow. That is why you should use fgets().

    Like this:

    fgets(buffer, sizeof buffer, stdin);
    

    Note that I have passed the values sizeof buffer and stdin. sizeof buffer is to ensure we don't get a memory overflow. stdinis the stream that corresponds to the keyboard. So then we read safely data from the keyboard and you will have a working code.

    See references here: http://www.cplusplus.com/reference/cstdio/gets/ http://www.cplusplus.com/reference/cstdio/fgets/

    And also if you are interested there are other functions to read user inputs, such as scanf(): http://www.cplusplus.com/reference/cstdio/scanf/?kw=scanf