0

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.?
`

3
Contributors
3
Replies
5
Views
4 Years
Discussion Span
Last Post by niyasc
0

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

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.