Domanda

I would like to perform the following actions:

  1. Read the first line from a file and store it in a variable N.
  2. Read the file lines for 0 <= i < N and store them in a array to sort them later.

NOTE: if N == 0 then it should exit.

Here is my code:

FILE *f = fopen(argv[1], "r");

while (true)
{    
    fgets (mystring , 100 , f);
    cout << mystring;
    fseek(f, 1, SEEK_CUR);
    N = atoi(mystring);    

    if (N == 0)
    {
        cout << "\n Exit";
        exit(0);
    }

    for (i = 0; i < N; i++)
    {
        bzero(mystring, sizeof(mystring));
        fgets (mystring , 100 , f);
        fseek(f, 1, SEEK_CUR);
        a[i] = atoi(mystring);
        cout << a[i];
    }
}

It reads the first file (which contains N) correctly, but then it reads the file as 00000000000 so that the next value of N becomes 0 and it exits the loop.

Here is my input file:

10
1
2
3
4
5
6
7
5
3
3
5
1
2
5
5
6
0

Could anyone please help me resolving this issue?

È stato utile?

Soluzione

Got it!

Remove extra fseek(f, 1, SEEK_CUR);

Each fgets() reads line including new line. So the file pointer points at the beginning of the new line. Your fseek moves the pointer to the next character which is a new line character (\n). atoi() of an empty string returns 0.

That will do help.

Now, there is one small thing that you make correct. If your mystring is declared as char mystring[100] then in each place you call fgets, change your 100 to sizeof(mystring). That is more correct.

I do not understand why you got so many negative points. I am upping your question.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top