Complementary task for topic: 5

M Nemeth · 2023-08-29 15:21:04.620218'

Simple strings: Length Counter

Simple strings: Length Counter

Write a C program that uses scanf() to read a string from the user and then calculates and displays the length of the entered string.

Hint: Strings are closed with '\0' character (End-of-String) and it is a char array. You can count the number of valid characters, that will give the length!

Solution
#include 

int main() {
    char str[100];
    int length = 0;

    printf("Enter a string: ");
    scanf("%99[^\n]", str); // Read the string with spaces

    // Calculate the length of the string
    while (str[length] != '\0') {
        length++;
    }

    printf("The length of the string is: %d\n", length);

    return 0;
}



Explanation
Explanation:

    The program uses a char array str to store the input string.

    The user is prompted to enter a string using printf().

    The string is read using scanf() with the %[^\n] format specifier, allowing the input to include spaces.

    The length of the string is calculated by iterating through the characters in the str array until the null terminator (\0) is encountered.
< < previous    next > >