Art of C programming

Getline

How to create a straightforward C program to capture a text line and determine its size.

Perfect for C beginners or those looking to enhance their programming skills.

                    
#include <stdio.h>

int main()
{
    int lim = 100;
    char s[100];
    int c, i;

    printf("Enter a string: ");
    for (i = 0; i < lim-1 && (c = getchar()) != '\n' && c != EOF; ++i)
        s[i] = c;
    s[i] = '\0';

    printf("String: %s\n", s);
    printf("Length: %d\n", i);
}
                    
                

Compile

cc getline.c -o getline

Run

./getline

Enter a string: Hello World!
String: Hello World!
Length: 12

Source code