Following is my code for reading from a file.

#include<stdio.h>
int main()
{
    char s[10][10];
    int i=0,j=0;
    FILE *ptr=fopen("input.txt","r");
    char c;
    while(fscanf(ptr,"%c",&c)!=EOF)
    {
        if(c=='\n')
        {
            s[i][j]=0;
            i++;
            j=0;
        }
        else 
        {
            s[i][j]=c;
            j++;
        }
    }
    s[i][j]=0;
    fclose(ptr);
    for(j=0;j<i;j++)
        printf("%s\n",s[j]);
    return 1;
}

and content of input.txt is
A->XAZ|Yz|z
X->xZ|x
Z->Xz

It is expected to get an output as in file.
But I'm getting an output like this .
A->XAZ|Yz|X->xZ|x
X->xZ|x
Z->Xz

Can anyone explain me that why this happens.?
`

Recommended Answers

All 3 Replies

Seems like the problem is due to insufficient size of the array s. Try changing you array size to s[10][12]

Why are you using fscanf() to read a single character? The overhead is tremendous. fgetc() was specifically made to read a character. It's small and concise.

Yes. It was problem with array size. Thanks for help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.