Command-Line Input with getline in C

 Command-Line Input with getline in C


The getline function allows you to read a line of input from the user, including spaces and other special characters. It dynamically allocates memory to store the input.


#include <stdio.h>

#include <stdlib.h>


int main() {

    char* line = NULL;

    size_t bufferSize = 0;

    ssize_t lineLength;


    printf("Enter a line of text: ");

    lineLength = getline(&line, &bufferSize, stdin);


    if (lineLength == -1) {

        printf("Error reading input.\n");

        return 1;

    }


    printf("Line length: %zd\n", lineLength);

    printf("Line: %s", line);


    free(line);


    return 0;

}

In this example, the getline function is used to read a line of text from the user. The function dynamically allocates memory to store the line and returns its length. After using the line, memory is freed using free.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...