-4

Implement an algorithm that reads a mathematical expression from the standard input and writes to Standard output if the expression is correctly bracketed.

I made the code but I do not know if it's okay how I used the file.

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

int main()
{
FILE *citire, *scriere; 
char expr[100];
int fe=0,i;


citire = fopen("in.txt", "rb");
scriere = fopen("out.txt", "wb");
fscanf(citire, "%s", &expr);

//input
i = 0;
while (expr[i] != '\0')        
{
    if (expr[i] == '(')
    {
        fe++;
    }
    else if (expr[i] == ')')
    {
        fe--;
        if (fe < 0) 
            break;
    }
    i++;
}
//output
if (fe == 0)
{
    fprintf(scriere, "DA\n");
}
else          
{
    fprintf(scriere, "NU\n");
}
fclose(citire);
fclose(scriere);
return 0;
}
alk
  • 69,737
  • 10
  • 105
  • 255

1 Answers1

0

To read/write from Standard In-/Output replace this

citire = fopen("in.txt", "rb");
scriere = fopen("out.txt", "wb");

by this

citire = stdin;
scriere = stdout;

and drop the two calls to fclose().

Then call the program like this

./a.out <in.txt >out.txt

Alternatively you could drop the FILE* variables at all and switch from using the general f*() functions to using the Standard-I/O related versions:

  • fscanf() --> scanf()
  • fprinf() --> printf()
alk
  • 69,737
  • 10
  • 105
  • 255