Indexing in arrays when using fgets

780 Views Asked by At

I'm teaching myself programming. I read that a string stored in an array of characters can be indexed to extract the nth character.

However, I've been trying to solve this for hours: I realized trying to solve an exercise that I can only access the first character of the array myarray[0]; whereas the rest of index (1,2,3...) values will return nothing. However, if I use the puts function it does return the whole string. Curious thing: strlen is returning the length of my array +1.

example:

    int main (void)
    {
    char myarray[1000]={0};
    int i;

    fgets(myarray,1000,stdin);
    for(i=0;i<strlen(myarray);i++)
       printf("myarray[%d]:%c\n",i,myarray[i]);
    printf("\n");
    printf("strlen:%d\n",strlen(myarray));
    puts(myarray);
    return 0;
    }

input: 6536

output:

strlen:5
myarray[0]:6
myarray[1]:
myarray[2]:
myarray[3]:
myarray[4]:
6536
4

There are 4 best solutions below

0
On

The strlen counts the '\n' at the end of the string. You can "fix" it with strtok:

strtok(myarray, "\n");
1
On

You are getting this result most probably because of undefined behavior of your program. You are using wrong format specifier to print a size_t type (strlenreturn size_t type). Change the format specifier to %zu.

Also note that in for loop you need to declare i as size_t type.
Here is the fixed code: http://ideone.com/0sMadV

0
On

fgets writes a newline character \n into the buffer to represent newlines in the input stream. Thus strlen returns 5.

0
On

The actual output is :

6536
myarray[0]:6
myarray[1]:5
myarray[2]:3
myarray[3]:6
myarray[4]:


strlen:5
6536

As you can see, myarray[4] stores the newline (due to fgets). Also, it would be better to calculate strlen once by placing it above the loop, instead of in every iteration.

From here:

char *fgets(char *restrict s, int n, FILE *restrict stream);

The fgets() function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.

A simple way is to for strlen(var)-1. Another way is to remove the newline with null terminating character:

if (myarray[length - 1] == '\n')
    myarray[length - 1] = '\0';

where length = strlen(myarray);