OrangeBike
OrangeBike

Reputation: 145

How to write a code to read input in separate lines from an input file and do the same thing this code does in C

I wrote this code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char numbers[2001];
    char a[1000], b[1000];
    int int1, int2, i, n = 0;
    int sum, difference;

    fgets(numbers, sizeof(numbers), stdin);

    for (i = 0; i < 1000; i++)
    {
        if (numbers[i] != ' ')
        {
           a[i] = numbers[i];
        }
        else if (numbers[i] == ' ') {
            i += 1;
            b[n] = numbers[i];
            for (n = 1; n < 1000; n++)
                b[n] = numbers[n+i];
        }


    }

    int1=atoi(a);
    int2=atoi(b);

    sum = int1 + int2;
    difference = int1 - int2;
    printf("%d\n%d", sum, difference);

    return 0;
 }

But there are several lines of 2 numbers in input file. And I want the program to find the sum and difference for each line and print them.

Here is an example of an input:

12 45
36 111
9 5
153 6

output:

57
33
147
-75
14
4
159
147

Upvotes: 0

Views: 50

Answers (1)

Hitokiri
Hitokiri

Reputation: 3689

You can use sscanf for getting the number from the string, it's more simple:

    FILE * fp = fopen("input.txt", "r");
    if (!fp) {
       return -1;
    }
    int i = 0;
    while(fgets(numbers, sizeof(numbers), fp)) {
        sscanf(numbers, "%d %d", &a[i], &b[i]);
        printf("sum = %d\n", a[i]+b[i]);
        printf("diff = %d\n", abs(a[i] - b[i]));
        i++;
    }

You should change the type of a and b from char to int for the big number.

int a[1000], b[100];

Because the numbers in my code is the line of the input file, and it content of 2 number, so you can decrease its size:

char numbers[256]; // for example.

The complete for test:

int main(void) {
    char numbers[256];
    int a[1000], b[1000];
    FILE * fp = fopen("input.txt", "r");
    if (!fp) {
       return -1;
    }
    int i = 0;
    while(fgets(numbers, sizeof(numbers), fp) && i < 1000) {
        sscanf(numbers, "%d %d", &a[i], &b[i]);
        i++;
    }

    for(int j = 0, j < i; j++) {
        printf("%d %d\n", a[j], b[j]);
        printf("sum = %d\n", a[j]+b[j]);
        printf("diff = %d\n", abs(a[j] - b[j]));
    }
    return 0;
}

The input and output:

#cat input.txt
12 45
36 111
9 5
153 6

./test
12 45
sum = 57
diff = 33
36 111
sum = 147
diff = 75
9 5
sum = 14
diff = 4
153 6
sum = 159
diff = 147

Upvotes: 1

Related Questions