PLEASE READ IN EACH LINE AND USE EVAL each line a ata file c
PLEASE READ IN EACH LINE AND USE EVAL
each line: a ata file called \"mathfile.dat\" stores three characters on each operand la single digit number), an operator la one character op as+, , and then another operand (a single digit number). For example, it might look like this: 16. A data file called \"mathfile.dat stores three characters on haracter operator, such >>type mathfile.dat 5+2 8-1 3+3 You are to write a script that will use fgetl to read from the file, one line at a time, perform the specified operation, and print the result.Solution
mathfile.dat
5+2
4-3
8-1
3+3
mathfile.m
% This script reads a text file and evaluates the expression on each line
fileid = fopen(\'mathfile.dat\');
if fileid == -1
disp(\'File open not successful\')
else
while ~feof(fileid)
str = fgetl(fileid);
result = eval(str);
x = str2num(str(1));
operator = str(2);
y = str2num(str(3));
fprintf(\'%d %c %d = %d\ \',x,operator,y,result)
end
closeresult = fclose(fileid);
if closeresult == 0
disp(\'File close successful\')
else
disp(\'File close not successful\')
end
end
