scanfformatted-input

fscanf function not working


I'm currently writing a program that reads numbers from sets of 2 numbers from a text file and prints them out. I'd like to use the numbers to determine a GCD later, but I have to be able to scan them from the file first. The text file looks like this:

24      72
25      50
31      89
...

Tab is pressed between each number in the first row and each number in the second.

I've come up with this so far (commented out section is to be used for determining the GCD):

/*
File name: euclid.cpp
This program find the largest common multiple of two numbers using the Euclid  method.
*/

#include <stdio.h>
#include "genlib.h"
#include "simpio.h"

int main()
{
    FILE *input;
    long num1=0, num2=0, orinum2=0, rem=0, gcd=0;
    int i=0, size=0;
    char temp;

    input=fopen("Euclid.txt", "r"); 

    while((temp=getc(input))!=EOF)
    {
        if(temp=='\n') size++;
    }
    size++;

    while(i<size)
    {
        fscanf(input, "%d\t%d%[^\n]", &num1, &num2);
        printf("%d\t%d\n", num1, num2);
        orinum2=num2;
/*      while (true)
        {
            rem=num1%num2;
            if (rem==0)
            {
                gcd=num2; break;
            }
            else
            {
                num1=num2;
                num2=rem;
            }
        }
        printf("The GCD of %d and %d is %d.\n", num1, orinum2, gcd);
*/      i++;
    }

    fclose(input);

}

Every single webpage and resource I have checked dictates that this should work, but for some reason it just isn't.


Solution

  • fscanf will "return the number of input items successfully matched and assigned":

    #include <stdio.h>
    
    int main()
    {
        FILE *input = fopen("input.txt", "r"); ;
        int num1, num2;
    
        while(fscanf(input, "%d %d", &num1, &num2) > 0)
            printf("%d\t%d\n", num1, num2);
    
        fclose(input);
    }
    

    The pattern ("%d %d") will match and assign two integers, separated by any number of whitespace characters.

    Whitespace characters include your tab (\t), and newline (\n).