Home > Blockchain >  how to get input size with fgets?
how to get input size with fgets?

Time:09-27

I have a problem with checking the size of input string with fgets. what I wanted to do is

If the input size is bigger then the buf_len then set "more" to 1 else 0 .

but I am not sure what is the right way to check the input size.

int read_stdin(char *buf, int buf_len, int *more)
{    // buf = malloc(10), buf_len = 10 , more = 1,

    fgets(buf, buf_len, stdin) ;
    size_t input_buf_len = strlen(buf);
    printf("size of input: %zu \n",sizeof(input_buf_len)); // prints 8
    printf("buf: %lu \n",sizeof(buf)); // prints 8
    printf("buf_len:%lu \n",sizeof(buf_len)); // prints 4
    printf("stdin:%lu \n",sizeof(stdin));// prints 8
        if (input_buf_len > buf_len)
        {
            *more = 1;
            printf("buf > buf_len\n");
        }
        *more = 0;
         printf("buf < buf_len \n");
     return sizeof(buf);
}

it does not matter how big the input length is , could be 1 or 20 , still prints the same number as the comment in the code.

CodePudding user response:

The fgets call reads text up to a newline and includes the newline in the read text. If what was read by fgets does not end in a newline character, that means that there's more text to be read on that line.

If fgets returns NULL, that means it reached EOF and that no characters have been read.

CodePudding user response:

fgets() reads user input and stops when it reads a newline character. It returns:

  • A pointer to the string read if it succeeds
  • NULL if it fails or if it encounters an EOF

To get input size, first you have to replace \n by a null-terminator, then call strlen(). This is because strlen() stops when it encouters a null-terminator, but doesn't when it encounters a newline:

if (!fgets(buf, buf_len, stdin)) {
    // fgets failed...
} else {
    buf[strcspn(buf, "\n")] = '\0';
    size_t input_buf_len = strlen(buf);
    printf("Input length: %ld", input_buf_len);
}
  •  Tags:  
  • c
  • Related