Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <windows.h>
- #include <stack>
- #include <string>
- #include <sstream>
- #include <cctype>
- using namespace std;
- int main() {
- SetConsoleOutputCP(1251);
- SetConsoleCP(1251);
- stack<int> s{};
- string input{}, part{};
- cout << "Введіть вираз у зворотному польському записі:" << endl;
- getline(cin, input);
- stringstream ss(input);
- while (ss >> part) {
- if (part == "+" || part == "-" || part == "*" || part == "/") {
- if (s.size() < 2) {
- cout << "У виразі недостатньо чисел для виконання операції." << endl;
- return 0;
- }
- int b = s.top();
- s.pop();
- int a = s.top();
- s.pop();
- if (part == "+") {
- s.push(a + b);
- }
- else if (part == "-") {
- s.push(a - b);
- }
- else if (part == "*") {
- s.push(a * b);
- }
- else if (part == "/") {
- s.push(a / b);
- }
- }
- else {
- try {
- int num = stoi(part);
- s.push(num);
- }
- catch (...) {
- cout << "'" << part << "' не є числом або оператором." << endl;
- return 0;
- }
- }
- }
- if (s.size() == 1) {
- cout << "Результат: " << s.top() << endl;
- }
- else {
- cout << "Було введено неправильну кількість чисел або операцій." << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement