I am newbie in C programming and I have a easy assigment but I coul not do that. I need to read two number from a file, add them, print them that is all. Here is the my code.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
	FILE *fp;
	fp = fopen("erogol.k","r");
	char a =fgetc(fp);	
	int aInt = atoi(&a);
	char b =fgetc(fp);
	int bInt = atoi(&b);
	printf("%d \n",bInt+aInt);
	return EXIT_SUCCESS;
}

My File has "9 4" and I need to take each number 9 and 4 them sum them but the program does not work.

Can you help me?

Recommended Answers

All 7 Replies

Your going about this the wrong way. Try using fgets() instead of fgetc().

#include <stdio.h>
#include <stdlib.h>

#define STR_SIZE 10

int main(void) 
{
	FILE *fp;
	char ch[STR_SIZE];
	int aInt;
	int bInt;

	fp = fopen("erogol.k","r");

	fgets(ch, STR_SIZE, fp);	
	aInt = atoi(ch);
	fgets(ch, STR_SIZE, fp);	
	bInt = atoi(ch);

	printf("%d \n",bInt+aInt);

	return EXIT_SUCCESS;
}

Both numbers are on the same line, so you only need one fgets call, I think. Then you can get the digits from the string or use sscanf (but that's probably overkill).

both number are in the same string, this is what you do

int main(void) 
{
	FILE *fp;
	char ch[STR_SIZE];
	int aInt;
	int bInt;

	fp = fopen("erogol.k","r");

	fgets(ch, STR_SIZE, fp);	
	aInt = atoi(ch[0]);
        bInt = atoi(ch[1]);
	printf("%d \n",bInt+aInt);

	return EXIT_SUCCESS;
}
aInt = atoi(ch[0]);
bInt = atoi(ch[1]);

Except that there's a space at position 1.

If the numbers are on the same line..

#include <stdio.h>
#include <stdlib.h>

#define STR_SIZE 10

int main(void) 
{
	FILE *fp;
	char ch[STR_SIZE];
	int aInt;
	int bInt;

	fp = fopen("erogol.k","r");

	fscanf(fp, "%s", ch);	
	aInt = atoi(ch);
	fscanf(fp, "%s", ch);		
	bInt = atoi(ch);

	printf("%d \n",bInt+aInt);

	return EXIT_SUCCESS;
}

C'mon, guys, think!

Any guesses what fscanf(fp, [B]"%d"[/B], &bInt); might do?

We don't have to think...your here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.