c - calculating file content separately

Well, so far I've opened a file. The file output looks like this:


Credit:
300
20
100
45
Cash:
150
200
30
10
25


Everything is fine with the printing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int money;
	char words[8] = {0};
	FILE *fptr;
	
	if((fptr = fopen("credicash.txt", "r")) == NULL)
	{
		perror("Error! opening file");
		exit(1);
	}
	
	while(EOF != fscanf(fptr, "%s %d", words, &money))
	{
		printf("%s \n%d \n", words, money);
		
		//calculation here.
	}
}


I just don't know how to calculate the credite and cash separately without calculating it all together. And by calculating I mean simple addition.
Do you have to use C or can you use C++?
you will have to look at the data you have read, which you read into variables with yuor fscanf function. If this is C, something like
if(strcmp(words, "credit") == 0)
{
totalcredit += money;
}
else if ... //check "cash" and do the same etc.

I'm working on C, but I guess it would be fine to see on C++.
Here's a possibility in C:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char line[500];
    double cash = 0, credits = 0;

    FILE *fin = fopen("credicash.txt", "r");
    if (fin == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    fscanf(fin, "%s", line);  // read "Credit:"

    // Sum the credits
    while (fscanf(fin, "%s", line) == 1) {
        if (strcmp(line, "Cash:") == 0) // stop when we find "Cash:"
            break;
        credits += atof(line);
    }

    // Sum the cash
    while (fscanf(fin, "%s", line) == 1)
        cash += atof(line);

    printf("Credits: %9.2f\n", credits);
    printf("Cash   : %9.2f\n", cash);

    return 0;
}

Topic archived. No new replies allowed.