Thread: Strlen

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    58

    Strlen

    Hello. When i am using i read text from file and when i use strlen function I always getting sting length longer by 1. Is there any alternative way to count string length except -1 because I need to find shortest line in .txt file.

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        FILE *fp;
        char filename[50];
        char str[100];
        int a,min=0;
        printf("Enter file name \n");
        scanf("%s",&filename);
        if ((fp=fopen(filename,"r"))==NULL)
        {
            printf("Error \n");
            system("pause");
            exit(1);
        }
      while (!feof(fp))
        {
            fgets(str, 99, fp);
             a=(strlen(str));
             if (a=1)
             if (min=0)
             min=a;
             else
             if (min<a)
             min=a;
       }
        printf ("%d", min);
        system("pause");
    
    }
    of course this isn't complete code because i faced this problem.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > if (a=1)
    This is assignment, not comparison.

    > while (!feof(fp))
    See the FAQ on why using feof() to control a loop is bad.

    Typically, we do
    while ( fgets( str, sizeof(str), fp) != NULL )
    to read each line in turn, and exit when eof is reached.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    >A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str.

    in other words, strlen is counting the newline character at the end of each line. since each line has a newline, you can just use the length as is, or subtract 1 if you like. except the last line may not have one, so you might need to check the end of each line whether to subtract 1 or not.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strlen
    By veronicak5678 in forum C++ Programming
    Replies: 15
    Last Post: 02-23-2008, 12:24 AM
  2. strlen help
    By stewie1986 in forum C Programming
    Replies: 10
    Last Post: 12-04-2007, 12:15 PM
  3. strlen()
    By BoneXXX in forum C Programming
    Replies: 6
    Last Post: 06-17-2007, 01:32 AM
  4. strlen()
    By exoeight in forum C Programming
    Replies: 9
    Last Post: 04-01-2005, 10:18 AM
  5. Why O why, strlen?
    By Sebastiani in forum C Programming
    Replies: 11
    Last Post: 08-24-2001, 01:41 PM