-1

This program doesnt work with CodeBlocks because its an error on line 13 (fgets).

/*
Sams teachyourself C in one hour a day
page 84 program 3
*/
#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;
}

Please help me, its a program from a smart C book and I wonder why it does not work?

  • 1
    https://www.cplusplus.com/reference/cstdio/fgets/ It's not working because `fgets` is called the wrong way. – klutt May 09 '21 at 14:04
  • 1
    What book is it btw? – klutt May 09 '21 at 14:05
  • 1
    Methodius5510, research `char *fgets(char * restrict s, int n, FILE * restrict stream);`. – chux - Reinstate Monica May 09 '21 at 14:12
  • Methodius5510, `strlen( buffer )` returns a type `size_t`. `"%d"` expects an `int`. If this is a true copy of code from "Sams teachyourself C in one hour a day", I recommend a different book. Or is the code a [transcription error](https://stackoverflow.com/questions/67450337/function-and-its-definition-outside-main-doesnt-work#comment119219880_67450363)? – chux - Reinstate Monica May 09 '21 at 14:20
  • Is it possible to change %d to something that works with size_t? Btw. this book has many pages and that is one reason that I like it. When it comes to fgets it seems to be a function for files, not to work just inside a program. Am I right? I got it the program to work with the function gets (gets( buffer );) instead of fgets! It must be a typo in the book. – Methodius5510 May 09 '21 at 14:55
  • @Methodius5510 `%zu` is the correct format specifier is for `size_t`. And `fgets` can be used for input in the program, and should be. The correct call to `fgets` here would be `fgets(buffer, sizeof buffer, stdin);` And *please* do not use `gets`. It's deprecated as of C99 and removed as of C11. See [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036) If your book were to be telling you to use `gets`, it would be a *very* bad book. – mediocrevegetable1 May 09 '21 at 15:00

1 Answers1

0

fgets doesn't work like that, it takes 3 parameters,

char *fgets(char *str, int n, FILE *stream);

str is the pointer to the string buffer in this case

n is the size of the string, 256 in this case

the stream is mostly just - stdin

So in summary just change fgets( buffer ); to fgets(buffer, 256, stdin);

Also it's a good idea to create a function to get strings more efficiently:


void getStr(char str[], int size)
{
    fgets(str, size, stdin);
    *(str + strcspn(str, "\n")) = '\0';
    *(str + size-1) = '\0';
}

It will get you the string and clean it up a little, you will need #include <string.h> however.