Patel
Patel

Reputation: 87

String length Error

I am reading the string from the stdin using fgets function and then trying to print the length of the string, But I am always getting the length of the string as 1 always for the first time Here is my code

#incldue<stdio.h>
#include<string.h>
int main(void)
{
   printf("\n Enter the no of test cases");
   scanf("%d",&t);
   int i,j;
   for(i=0;i<t;++i)
   {
     char song[500],val[28];
     int k=0,x=0;
     fgets(song,500,stdin);
     int len=strlen(song);
     printf("\nlen=%d",len);
   }
  return 0;
}

I am always getting 1 as the length for the first test case :/ Please suggest where i am going wrong

Upvotes: 2

Views: 1978

Answers (3)

David C. Rankin
David C. Rankin

Reputation: 84642

When using scanf (or its relatives), it is important to check the return of the function. scanf returns the number of input values correctly matched and assigned. If there are inappropriate characters or insufficient characters, scanf will experience a matching or input failure. A quick if statement will suffice:

    if (!scanf ("%d", &t)) {
        fprintf (stderr, "error: invalid type or number for test cases.\n");
        return 1;
    }

As also noted, fgets will read and include in song the trailing newline character. Generally, you will want to remove the trailing newline to prevent having stray newlines scattered through various strings within your code. (not to mention looking at a length=5 for data is a bit strange) A simple method for removing the newline after your call to fgets is:

            len = strlen (song);
            while (len && song[len-1] == '\n')  /* strip newline */
                song[--len] = 0;

Putting together the test of scanf return, emptying the input buffer, and stripping the newline after fgets, your code would look similar to:

#include <stdio.h>
#include <string.h>

int main (void)
{
    int c = 0;
    int i = 0;
    int t = 0;

    printf ("\n Enter the no of test cases: ");
    if (!scanf ("%d", &t)) {
        fprintf (stderr, "error: invalid type or number for test cases.\n");
        return 1;
    }
    while ((c = getchar()) != '\n' && c != EOF);

    for (i = 0; i < t; ++i) {

        char song[500] = { 0 };
        size_t len = 0;

        if (printf ("\n    case [%d] : ", i) && fgets (song, 500, stdin))
        {
            len = strlen (song);
            while (len && song[len-1] == '\n')  /* strip newline */
                song[--len] = 0;
        }
        printf ("         len : %zu\n", len);
    }

    printf ("\n");
    return 0;
}

Output

$ ./bin/scanf_rd_int

 Enter the no of test cases: 2

    case [0] : this is case one - 28 chars.
         len : 28

    case [1] : this is case two -- 29 chars.
         len : 29

Upvotes: 0

Alex
Alex

Reputation: 3464

Include \n in scanf input string (and in C declare variables at the beginning of the block { }).

Also notice the len will include the \n char.

#include<stdio.h>
#include<string.h>
int main(void)
{
    int t, i;
    printf("Enter the no of test cases: ");
    scanf("%d\n",&t);
    for(i=0;i<t;++i) {
        char song[500];
        int len;

        fgets(song,500,stdin);
        len=strlen(song);
        printf("len=%d\n",len);
    }
    return 0;
}

update

If you need to handle weird input just use fgets (\n removed from len).

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
    char song[500];
    int t, i, len;  
    printf("Enter the no of test cases: ");
    fgets(song,500,stdin);
    t = atoi(song);
    for(i=0;i<t;++i) {
        fgets(song,500,stdin);
        if ((len=strlen(song)) > 0) {
            song[--len] = '\0';
            printf("len=%d\n",len);
        }
    }
    return 0;
}

Upvotes: 3

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

You are not clearing the input buffer. After giving the input value to first scanf newline will be there. So fgets will not get the input from the user. Newline will be placed in that buffer in a first(song[0]) position. So this is the reason strlen returns as value 1.

Make this line before the fgets.

int c;
if ( i == 0 )
    while((c=getchar()) != '\n' && c != EOF );
fgets(song,500,stdin);

Or else place this line after getting the input from the scanf.

scanf("%d",&t);
while((c=getchar()) != '\n' && c != EOF );

Upvotes: 5

Related Questions