0

This is a part of my 'Phonebook' program.

void refresh(){

    char name[300][50], tmpa[50];
    int i = 0, j, k, num[300], tmpb;

    fp = fopen("Phonebook.txt","r");

    while (!feof(fp)){

        fscanf (fp, "%s %d", name[i], &num[i]);

        ++i;

    }

    for (j = 0; j <= i; ++j){

        for (k = 0; k < i; ++k){

            if ((strcmp(name[k], name[k+1])) > 0){

                strcpy(tmpa, name[k+1]);
                strcpy(name[k+1], name[k]);
                strcpy(name[k], tmpa);

                tmpb = num[k+1];
                num[k+1] = num[k];
                num[k] = tmpb;

            }

        }

    }

    fclose(fp);

    fp = fopen("Phonebook.txt","w");

    for (k = 0; k <= i; ++k){

         fprintf(fp, "%s %d\n",name[k],num[k]);

    }

    fclose(fp);

    menu();

}

It works just fine. It sorts the number in list just as I wanted. But when I ran the program, everything was sorted but on the top line of the file, there was this : 0 +8800

Why is this happening?

Anik Shahriar
  • 151
  • 1
  • 11
  • @kaylum That's not what I meant. The reading from file is fine. But why does the program add an extra number in the file? – Anik Shahriar Dec 06 '16 at 05:19
  • Why do you have `j <= i` and `k <= i` instead of `j < i` and `k < i`? – GMichael Dec 06 '16 at 05:19
  • `while (!feof(fp)){ fscanf (fp, "%s %d", name[i], &num[i]);` --> `while (EOF != fscanf (fp, "%s %d", name[i], &num[i])){`, `k < i` --> `k < i -1`, `k <= i` --> `k < i` – BLUEPIXY Dec 06 '16 at 05:20
  • Did you read the linked question? The result of that bug is that the loop will execute one more time than it should. Meaning one of the `name` and `num` entries contains undefined data. – kaylum Dec 06 '16 at 05:20
  • @AnikShahriar: because [`while (!feof(file))` is **always** wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong). You can easily see if you have your program print the data as it is read — which is one of the most basic debugging techniques. Check that the program is processing what you think it is processing. – Jonathan Leffler Dec 06 '16 at 05:20
  • @GMichael I used j <= i so that the loop continue as much time as i. And 'k<=i' was used for printing the name and num array's datas into the text file. – Anik Shahriar Dec 06 '16 at 05:22
  • @AnikShahriar But the last `i` value is irrelevant. You should not use it – GMichael Dec 06 '16 at 05:23
  • But how should I do it then? – Anik Shahriar Dec 06 '16 at 05:26
  • Okay problem solved. I used k < i -2 and j < i - 1. And it worked. – Anik Shahriar Dec 06 '16 at 05:29

0 Answers0