-2

Having a doubt regarding a very simple C code. I wrote a code to calculate the length of a string without using the strlen function. The code below works correctly if i enter a string with no spaces in between. But if i enter a string like "My name is ---", the length shown is the length of the word before the first white space, which in the example, would be 2. Why is that? Aren't white space and null character two different characters? Please guide me as to how i can change the code so that the entire string length is returned?

char s[1000];
int length = 0;
printf ("Enter string : ");
scanf ("%s", s);
for (int i = 0; s[i] != '\0'; i++)
  {
    length++;
  }
printf ("Length of given string : %d", length);
Sangeetha
  • 485
  • 2
  • 9
  • 24

2 Answers2

2

It is because scanf with %s reads until it finds white space.

from man scanf

Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

If you want read until \n including white space you can do as below.

scanf("%999[^\n]", s);

Or you could use fgets.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
-2

scanf reads the data until "\0" or "\20". So use "fgets" method which reads the data until "\n" (next line) with "stdin",

Example Program:

#include <stdio.h>

int main() {

    char s[100];
    printf("Input String: ");
    fgets(s, sizeof(s), stdin);
    printf("\nLength of the string is = %d", printf("%s"), s);
    return 0;
}
Eswaran Pandi
  • 602
  • 6
  • 10
  • 1
    [why-is-the-gets-function-so-dangerous-that-it-should-not-be-used](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – kiran Biradar Oct 06 '18 at 20:07