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?

Dani AI

Generated

Briefly: for a college-style task where each input line is a single binary operation (like 5 + 7), use a line-based read + robust token parsing and write results with fprintf to an output file. is correct that a full expression evaluator (parentheses, precedence, unary operators everywhere) is more work; for the simpler per-line a op b case ’s scanf approach is fine, but the fgets/strtod pattern below gives better error handling and lets you write results to another file easily.

/* read input.txt, write results to results.txt */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main(void) {
    FILE *fin = fopen("input.txt", "r");
    FILE *fout = fopen("results.txt", "w"); /* use "a" to append */
    if (!fin || !fout) { perror("fopen"); return 1; }

    char line[256];
    while (fgets(line, sizeof line, fin)) {
        line[strcspn(line, "\r\n")] = 0; /* trim newline */
        char *p = line, *end;
        double a = strtod(p, &end);
        if (end == p) { fprintf(fout, "Parse error: %s\n", line); continue; }
        p = end; while (isspace((unsigned char)*p)) p++;
        char op = *p++;
        while (isspace((unsigned char)*p)) p++;
        double b = strtod(p, &end);
        if (end == p) { fprintf(fout, "Parse error: %s\n", line); continue; }

        if (op == '/' && b == 0.0) { fprintf(fout, "Division by zero: %s\n", line); continue; }
        double r = (op == '+') ? a + b :
                   (op == '-') ? a - b :
                   (op == '*') ? a * b :
                   (op == '/') ? a / b : 0;
        fprintf(fout, "%s = %g\n", line, r);
    }

    fclose(fin); fclose(fout);
    return 0;
}

Troubleshooting and tips:

  • Use "w" to overwrite the output file or "a" to append. Always check fopen return values.
  • strtod handles decimals and leading -; check the end pointer to detect malformed lines.
  • Trim long input lines or increase the buffer if needed. Handle blank lines by skipping them.
  • For in-place replacement of the input file, write to a temp file and rename() it after successful processing.
  • If you later need full-expression support (operator precedence, parentheses), look into implementing the shunting-yard algorithm or using a small expression parser — that’s a bigger step beyond this simple per-line approach.

Recommended Answers

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, networking, learning, and sharing knowledge.