1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Rep Power

    Help! C program not working :)

    Hi there guys! I'm trying to build up a program, but it doesn't work... I'm not very expert at C programming, thus I need your help please! :)

    I've got a first file (let's call it FIRST), which is structured as follows: the first column represents row number (i), the second column represents a datum (a1) and the third column represents another datum (b1).

    1 6 7
    2 2 3
    3 2 5
    4 1 6
    5 9 9

    Then I've a second file (let's call it SECOND) which is structured quite the same: first column represents a datum (a2) and the second one represents another datum (b2).

    6 7
    1 6
    2 1

    Basically, I wanna know when the couple (a2,b2) of the SECOND file coincides with one of the couples (a1,b1) of the FIRST file and hence print the row number (i) at which I have this correspondence (in this case it should print the numbers 1 and 4, at which the couples are the same).

    Well, I thought of two while cycles, i.e. I open the SECOND file and then for each row I open the FIRST file, looking for couple correspondence and printing the right rows... but it doesn't work, cause it stops at the first row of FIRST file... where's the problem??


    fscanf(SECOND, "%d %d", &a2, &b2);


    fscanf(FIRST, "%d %d %d", &i, &a1, &b1);

    if(a1==a2 && b1==b2){printf("%d\n", i);}


    Thank you in advance! Hope it is clear... sorry for the very stupid question and excuse me for my terrible english, but I'm italian!! :tntworth:
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Rep Power
    > while(!feof(SECOND)){
    > fscanf(SECOND, "%d %d", &a2, &b2);
    First, you should write this as
    while ( fscanf(SECOND, "%d %d", &a2, &b2) == 2 )

    The other thing to do, since you're reading FIRST repeatedly, is to put in
    before you try to read it.

    This will make sure you read FIRST from the start of the file, for every pair of integers read from SECOND.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo