fscanf() does not differentiate between rows. So you will be better off not using that function at all. Instead, I would use fgets() to read one row at a time then parse the string that was read.
char line[80];
char *ptr = 0;
int i = 0;
while( fgets(line, sizeof(line), f) != NULL)
{
// clear the array
memset(v,0,sizeof(v));
i = 0;
// extract numbers from line string
ptr = strtok(line," ");
while( ptr != NULL)
{
// insert into array
v[i] = atoi(ptr);
++i;
// get next number from the string
ptr = strtok(NULL, " ");
}
// now do something with these numbers
}
From a purely style issue, I would not use
memset() nor
strtok().
memset() is not necessary because you should be using only the array values you've loaded so you shouldn't have problems with uninitialized variables. As for
strtok() I prefer to parse the values by hand with loops. For example:
do
{
fgets(line, sizeof(line), f) != NULL)
n = 0;
// skip leading whitespace
while (isspace(line[n])) n++;
i = 0;
do
{
// extract numbers from line string
v[i] = atoi(&line[n]);
// skip to next value
while (!isspace(line[n])) n++; // skip over this value
while ( isspace(line[n]))
{
if (line[n] == '\n') break; // isspace() sees \n as whitespace
n++; // skip over the spaces
}
} while( line[n] != '\n')
I feel I have more control over the input by doing essentially what
strtok() does anyway. As I said, purely a personal style issue.
Now, about your code:
#include<conio.h> //// should not use this header, not portable
#include<stdio.h>
main()
{
clrscr(); //// Not portable. Also in Standard C you cannot use
//// an executable command before your declarations
int v[10],v1[10],i=0,j,t,k,number,count=0;
FILE *f ;
f = fopen("numbers.inp", "r"); //// please use whitespace
do
{
i++;
fscanf (f, "%d", &v[i]); //// please use whitespace for readability
count++;
}
while((number=getc(f))!=EOF);
As
ADragon said,
fscanf() cannot distinguish end of lines. So you just read
all the numbers into your 10-value array and corrupted memory.
One thing you might want to consider for debugging is using
printf()'s to display pertinent values as your program executes. Then you would have seen immediately that
i was getting too large for your array. You still may not know how to fix it, but at least you know what's happening.