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?

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).

Edited 5 Years Ago by jonsca: n/a

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;
}

Edited 5 Years Ago by dnambembe: n/a

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?

Edited 5 Years Ago by WaltP: n/a

This article has been dead for over six months. Start a new discussion instead.