Search code examples
cgetline

How to correctly use getline?


I was trying to use getline for user input and I manage to do so but each time I try to print everything after %s (like .) it gets put to the next line and I am also trying to get rid of trailing space characters input so I use the function below but for some reason this isn't working, any help, sorry for anything improper still learning:

Also can I print the contents of buff like an ordinary array (for loop) or is it different if I use getline?

/******************************************************************************



*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int trim (char *s)
{
    int i = strlen(s) - 1;
    while (i > 0){
        if (s[i] == ' '|| s[i] == '0'){
            i--;
        }
        else {
            break;
        }
    }
    s[i + 1] = '\0';
    printf("%d\n", i);
    return (strlen(s)); 
    
}

int main()
{
    char *buff = NULL;
    size_t sizeAllocated = 0;
    printf("Begining!!\n");
    printf("> ");
    size_t numCh = getline(&buff, &sizeAllocated, stdin);
    //numCh = trim(buff);
    printf("%s.", buff);
    
    free (buff);
    buff = NULL;
    
    return 0;
}

Thank you in advance for any help


Solution

  • You have several problems:

    numCh must be a ssize_t, which is the preferred type to handle errors on POSIX, use it :)

    Always check the result of getline

    int i = strlen(s) - 1; is very prone to errors because strlen returns an unsigned (size_t) and an empty string will give you a very big number (SIZE_MAX).

    Check if this helps:

    #define _POSIX_C_SOURCE 200809L
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #include <sys/types.h>
    
    static char *trim(char *str)
    {
        while (*str && isspace((unsigned char)*str))
        {
            str++;
        }
        if (*str)
        {
            // Here it is safe to use `strlen - 1` because
            // `if (*str)` ensures that there is a character
            char *end = str + strlen(str) - 1;
    
            while (*end && isspace((unsigned char)*end))
            {
                end--;
            }
            *(end + 1) = '\0';
        }
        return str;
    }
    
    int main(void)
    {
        char *str = NULL;
        size_t size = 0;
        ssize_t len = 0;
    
        if ((len = getline(&str, &size, stdin)) != -1)
        {
            const char *trimmed = trim(str);
    
            printf("<%s>\n", trimmed); // Use trimmed
        }
        free(str);
        return 0;
    }