0

I have to read text in from a file, then prompt for a value and search the file for this number. Once the file is read all the way through, I have to print the initial position and the number of times it appears. Obviously I do not just want the answer, but rather where my program went wrong because I am blind to it as of now.

My source code looks like this:

    int count, number, value;
    printf("What number are you looking for? ");
    scanf("%d",&value);

    FILE *fp = fopen("data.in","r");
    count = 0;
    while (!feof(fp)) {
        fscanf(fp,"%d",&number);
        if (number == value) {
            ++count;
            }
        }
    fclose(fp);

    printf("The number %d appears first at position %d in the file",value,number);
    printf("The number %d appears %d time(s)",value,count);

    return 0;
}

The data file I am reading from is:

3 8 33 75 25 10 41 8
10
 55 10 1 0 10
10 18

However, when I run the program it returns:

What number are you looking for? 10

The number 10 appears first at position 18 in the file

The number 10 appears 5 time(s)


What number are you looking for? -5

The number -5 appears first at position 18 in the file

The number -5 appears 0 time(s)

Any ideas? Again, I am not looking for the straight answer, rather a way for me to look for these issues both now and in the future.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
yup
  • 1
  • 6
  • You're not keeping track of the position of where the desired number was first seen (you're displaying a value from the file instead). You need to record that position the first time you see the desired number. – nobody Mar 08 '15 at 16:14
  • 1
    `while(!feof(fp))` is wrong. Replace `!feof(fp)` with the `fscanf` along with `==1` – Spikatrix Mar 08 '15 at 16:15

1 Answers1

3

After coming out from while loop number is always the last number i.e. 18 irrespective of number you are looking for.

The line fscanf(fp,"%d",&number); reads the number of each line and when loop terminates the number is assigned as 18.

Also read : “while( !feof( file ) )” is always wrong ?


Do something like following:

int pos = -1, curr_lno = 0 ; // Keep track of position
while (fscanf(fp,"%d",&number) == 1) 
{
    ++curr_lno ;
    if (number == value) 
    {
        pos = ( pos == -1 ) ? curr_lno : pos ;
        ++count;
    }
}
fclose(fp);

if ( count > 0 )
{
    printf("The number %d appears first at position %d in the file",value, pos );
}
Community
  • 1
  • 1
P0W
  • 46,614
  • 9
  • 72
  • 119
  • You'll get position 15 instead of 6 if you entered 10 as input.`"The number %d appears **first** at position %d in the file"`. – Spikatrix Mar 08 '15 at 16:22
  • @CoolGuy Sorry didn't notice that, fixed now. There can be easy way out though, left as an assignment for OP :D – P0W Mar 08 '15 at 16:29
  • Okay so I see where I went wrong with the initial and took a slightly path but with your guideline I figured it out!! Thank you so much!!! – yup Mar 08 '15 at 16:50