Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stack>
- #include <fstream>
- using namespace std;
- bool isBalanced(string str) {
- stack<char> charStack;
- int i = 0;
- bool continueCycle = true;
- while(i < str.length() && continueCycle) {
- char curr = str[i];
- if(curr == '(')
- charStack.push(curr);
- else if(curr == ')') {
- if(charStack.empty())
- continueCycle = false;
- else
- charStack.pop();
- }
- i++;
- }
- return continueCycle;
- }
- bool isStringContainsParentheses(string str) {
- return str.find('(') != -1 || str.find(')') != -1;
- }
- string readFile(string filePath) {
- string str;
- ifstream inputFile;
- inputFile.open(filePath);
- if (inputFile && getline(inputFile, str))
- inputFile.close();
- else
- cout << "Произошла ошибка при чтении файла. Убедитесь, что такой файл существует, либо проверьте имя файла."
- << endl;
- return str;
- }
- void saveResult(string resultStr) {
- string decision;
- while (decision != "Y" && decision != "N") {
- cout << "Сохранить результат в файл? (Y - сохранить, N - не сохранять)" << endl;
- cin >> decision;
- }
- if (decision == "Y") {
- ofstream outputFile;
- outputFile.open("output.txt");
- outputFile << resultStr;
- outputFile.close();
- cout << "Результат сохранен в файл output.txt" << endl;
- }
- }
- int main() {
- cout << "Данная программа проверяет баланс скобок в строке\n" << endl;
- string inputType;
- while (inputType != "C" && inputType != "F") {
- cout << "Введите C, если хотите ввести строку из консоли, или F, если хотите ввести строку из файла" << endl;
- cin >> inputType;
- }
- string resultStr, str;
- bool result = false;
- if (inputType == "C") {
- cout << "Введите строку, из которой необходимо удалить повторяющиеся символы" << endl;
- cin >> str;
- } else if (inputType == "F") {
- cout << "Введите путь к файлу" << endl;
- string filePath;
- cin >> filePath;
- str = readFile(filePath);
- }
- result = isStringContainsParentheses(str);
- if(result) {
- result = isBalanced(str);
- resultStr = result ? "Баланс скобок соблюдён" : "Баланс скобок не соблюдён";
- }
- else
- resultStr = "В строке отсутсвуют скобки";
- cout << resultStr << endl;
- saveResult(resultStr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement