You need to replace the ungetc function with another function that is not related to the c ci/o c++stream
#include <stdio.h>
#include <iostream>
double number(){ // считываем число
int res = 0;
for (;;)//бесконечный цикл
{
char c;
scanf_s("%c", &c);//записываем
if (c >= '0' && c <= '9')//условие, что используются только цифры
res = res *10 + c - '0';//для корректной записи числа
else {
ungetc(c, stdin);
break;//прерываем
}
}
return res;//возвращаем результат
}
double plmn();//чтобы компилятор увидел функцию в фактор
double skobki() {//скобки
char c;
scanf_s("%c", &c);
if (c == '(') {
double x = plmn();
return x;
}
else {//если не число,то
ungetc(c, stdin);//возвращаем символ
return number();
}
}
double factor() { // функция деления и умножения
double x =skobki();
for (;;) {
char c;
scanf_s("%c", &c);
switch (c) {
case '*': // если умножение
x *= skobki();
break;
case '/': // если деление
x /= skobki();
break;
default: //если неизвестный символ, то возвращаем в поток
ungetc(c, stdin);// возвращаем символ назад
return x;//возвращаем результат
}
}
}
double plmn() { // функция сложения и вычитания
double x = factor();
for (;;) {
char c;
scanf_s("%c", &c);
switch (c) {
case '+': // если сложение
x += factor();
break;
case '-': // если вычитание
x -= factor();
break;
default: //если неизвестный символ, то возвращаем в поток
ungetc(c, stdin);// возвращаем символ назад
return x; //возвращаем результат
}
}
}
int main()
{
double r = plmn();//вызов функций по порядку
printf("Result= %0.3f", r);//результат
}
The teacher forbade the use of streams, that is, ungetc is not suitable
0
1 answers
If such nonsense is set (you can't use a ready-made ungetc()
), then you need to emulate it. The easiest way is without buffering. Create your own "stream" (structure) in which you store a link to the file from which you read the next character (for example, with the read function) and a place for the character that you return to the "stream". If there is such a symbol, then when accessing the stream from the Get function, return it and set the -- no such symbol flag. If it is not present, the Get call returns the next character supplied by the read function. I hope the principle is clear, the rest of the details are up to you
-1
Author: jokerbot, 2020-07-19 13:15:20