Fcudber
Fcudber

Reputation: 21

Unable to take input beyond 4094 characters in a string

I was wodering that why the output is 4094 instead of 500000.

My input is 500000 long character file without any space. For eg:(vjdnvkk......abcf),with no. of char = 500000.

Here's the code :

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char s[500000];
    scanf("%s",s);
    printf("%d",strlen(s));
}

Upvotes: 1

Views: 940

Answers (2)

chux
chux

Reputation: 153458

Ideas:

  1. If the file truly consists of 500,000 non-white-spaces characters as claimed by OP: "My input is 500000 long character file", then code needs s to be 1 larger to prevent undefined behavior. Also use a matching specifier to print the length of s. @Schwern

    int main(void) {
        char s[500000 + 1];
        if (scanf("%500000s",s) == 1) {
          printf("%zd",strlen(s));
        }
    }
    
  2. OP claims a file exists "500000 long character file", yet this code does not read from a file, but from stdin. It is possible the unposted call of the program and its re-directed input is using some mechanism that limits the input to 4094.

  3. The "500000 long character file" simple has white-space about the 4094th character.

  4. As @Kuba Ober answered, the 4094th character (first location of the 0th one) is a null character. "%s" will surprisingly read multiple null characters as a null character is not a white-space.

Upvotes: 1

That's because 4095th byte of the input file is zero, and strlen counts up until it encounters the first zero.

Upvotes: 1

Related Questions