Sanket R
Sanket R

Reputation: 57

While calculating length of the string array, any string characters entered after space are ignored

a beginner here. I was trying to get the length of entered string without using strlen() function. I wrote a program that counts each character present in the entered string until it reaches the null terminator (\0).

After running the program, I was able to calculate the length of the first word, but not the entire sentence. Example : When I entered "Hello how are you?" , it calculated the length of the string only until "hello", the other characters after space were ignored. I want it to calculate the length of entire sentence.

Here's my code below.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

int main()
{
    char str1[100];
    int i = 0;
    int count = 0;

    printf("Enter the string you want to calculate (size less than %d)\n", 100);
    scanf("%s", str1);

    while (str1[i] != '\0') //count until it reaches null terminator
    {
        ++i;
        ++count;
    }
    
    printf("The length of the entered string is %d\n", count);

    return 0;
}

Upvotes: 0

Views: 105

Answers (2)

Wounder
Wounder

Reputation: 9

Modify the code like this, which will solve the problem.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <ctype.h>

#include <stdbool.h>

int main()
{
    char str1[100];
    int i = 0;
    int count = 0;

    printf("Enter the string you want to calculate (size less than %d)\n", 100);
       scanf("%[^\n]s", str1);

    while (str1[i] != '\0') //count until it reaches null terminator
    {
        ++i;
        ++count;
    }
    
    printf("The length of the entered string is %d\n", count);

    return 0;
}

Upvotes: 0

dbush
dbush

Reputation: 223972

The %s format specifier reads characters up until the first whitespace character. So you'll only read in one word a a time.

Instead, use fgets, which reads a whole line of text at a time (including the newline).

Upvotes: 2

Related Questions