Advertisement
msu_goncharenko

Untitled

Dec 8th, 2019
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.07 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <stack>
  4. #include <cmath>
  5. #include <set>
  6.  
  7. using namespace std;
  8.  
  9. string convert(string a)
  10. {
  11. string str;
  12. for(int i = 0; i<a.size(); i++)
  13. {
  14. if(a[i]!=' ') str.insert(str.end(), a[i]);
  15. }
  16. return str;
  17. }
  18. // проверка корректности выражения (последовательности чисел и знаков операции)
  19. bool correct_operation_signs(string a)
  20. {
  21. bool rightness = true; // булева переменная для фиксирования ошибочного выражения
  22. set<char> operand = {'+', '*', '/', '-', '^'};
  23. if ((operand.count(a[0])!= 0 && a[0]!='-') || operand.count(a[a.size()-1])!=0) // проверка символа на наличие операнда
  24. {
  25. rightness = false;
  26. }
  27.  
  28. else if (operand.count(a[a.size()]) != 0)
  29. {
  30. rightness = false;
  31. }
  32. /* если всё верно (в начале и в конце стоят не знаки), то выполняется цикл,
  33. который прогоняет строку на предмет двух символов подряд. */
  34. else
  35. {
  36. for (int i = 0; i < a.size(); i++)
  37. {
  38. if (operand.count(a[i])!=0 && operand.count(a[i+1])!=0)
  39. {
  40. rightness = false;
  41. }
  42. if((a[i] == '/') && (a[i+1] == '0')) // случай деления на 0
  43. {
  44. rightness = false;
  45. }
  46. }
  47. }
  48. return(rightness); // если нигде ошибки не было, то rightness=true
  49. }
  50.  
  51. // проверка корректности выражения (последовательности скруглых скобок)
  52. bool correct_parenthesis(string a)
  53. {
  54. bool rightness = true; // булева переменная для фиксирования ошибочного выражения
  55. stack<char> st; // стек в котором хранятся скобки
  56. set<char> opening_parenthesis = {'(', '{', '['};
  57. set<char> closing_parenthesis = { ')', '}', ']'};
  58.  
  59. for(int i = 0; i < a.size(); i++)
  60. {
  61. if (closing_parenthesis.count(a[i]) != 0)
  62. {
  63. if(st.size()!=0)
  64. {
  65. if ((a[i]==')' && st.top()=='(') || (a[i]=='}' && st.top()=='{') || (a[i]==']' && st.top()=='['))
  66. {
  67. st.pop();
  68. }
  69. else rightness = false;
  70. }
  71. else rightness = false;
  72. }
  73. else if (opening_parenthesis.count(a[i]) != 0)
  74. {
  75. st.push(a[i]);
  76. }
  77. }
  78.  
  79. if(st.size()>0 && rightness==true)
  80. {
  81. rightness = false;
  82. }
  83.  
  84. return rightness;
  85. }
  86.  
  87. int main()
  88. {
  89. string str; // исходная посл-ть
  90. getline(cin, str);
  91. str = convert(str);
  92.  
  93. if (correct_operation_signs(str) && correct_parenthesis(str))
  94. {
  95. cout << "Correct" << endl;
  96. return 0;
  97. }
  98.  
  99. cout << "Incorrect" << endl;
  100. return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement