0

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;
}
Sanket R
  • 57
  • 1
  • 7
  • Does this answer your question? [How can I scan strings with spaces in them using scanf()?](https://stackoverflow.com/questions/13726499/how-can-i-scan-strings-with-spaces-in-them-using-scanf) – phuclv Feb 06 '21 at 04:30

2 Answers2

2

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).

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Just curious to know if there is any other way without using fgets()? – Sanket R Feb 06 '21 at 02:37
  • @SanketR yes. There are lots of duplicates, just read them to see the alternatives [How do you allow spaces to be entered using scanf?](https://stackoverflow.com/q/1247989/995714), [Reading string from input with space character?](https://stackoverflow.com/q/6282198/995714), [Reading a string with spaces with sscanf](https://stackoverflow.com/q/2854488/995714)... – phuclv Feb 06 '21 at 04:34
  • @SanketR Curious, Why do you want to use something other than `fgets()`, the best function to read a _line_? – chux - Reinstate Monica Feb 06 '21 at 05:44
0

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;
}
Wounder
  • 9
  • 3
  • It worked, but don't know why "%" is highlighted in red in my Visual Studio Code IDE. What does it mean? – Sanket R Feb 14 '21 at 01:47