Hello guys, I need to make a C program that reads a text file for example the following sentence: 5 + 7, 10-15 ... (etc.), and show the result.
I managed to make it solve part of the problem. The program is making the sum of the first line. But just to rely on a digit (3 + 5).
And the program only reads up to the first line. Can anyone help me?

## All 6 Replies

How general is this intended to be? Because you're looking at essentially a mini-compiler that parses and evaluates mathematical expressions. In other words, it's not exactly a trivial project.

is for a college job.

That tells me exactly nothing. :P

if each line in the file is exactly

numberA someBinaryOp number B

then the problem is a breeze

//example file:

23.2 + -11.7
-11 * -77.9
128.99 / -11
23.91 - 123.99

// an example of processing the above example data ...

``````/* binaryOpsFromFile.c */  /* 2013-08-19 */

#include <stdio.h>

/* example file */

#define FNAME "numDat.txt"
/*
23.2 + -11.7
-11 * -77.9
128.99 / -11
23.91 - 123.99
55.5 / 0
.33 / 100
*/

void showAopB( double a, char op, double b )
{
double result = 0.0;
switch( op )
{
case '+' : result = a + b; break;
case '-' : result = a - b; break;
case '*' : result = a * b; break;
case '/' : if( b == 0.0 )
printf( "Invalid ==> " );
result = ( b == 0 ? 0 : a/b );
break;
default : printf( "%f %c %f NOT defined ... \n", a, op, b );
}
printf( "%fa %c %f = %f\n", a, op, b, result );
}

int main()
{
FILE* fin = fopen( FNAME, "r" );

if( fin )
{
double a, b;
char op;
while
(
fscanf( fin, "%lf", &a ) == 1 &&
fscanf( fin, " %c", &op ) == 1 && /* skip any leading ws */
fscanf( fin, "%lf", &b ) == 1

)
showAopB( a, op, b );

fclose( fin );
}
else printf( "\nThere was a problem opening file %s", FNAME );

printf( "\nPress 'Enter' to continue/exit ... " );
fflush( stdout ) ;
getchar();

return 0;
}
``````

thanks for the reply gave me new ideas, last question, if I want to store the answers in another txt file how can I do?

Be a part of the DaniWeb community

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