Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program task4;
- {$APPTYPE CONSOLE}
- {$R *.res}
- uses
- System.SysUtils,
- Contnrs;
- function IsBalanced(Str: String): Boolean;
- var
- i: Integer;
- Curr: Char;
- ContinueCycle: Boolean;
- Stack: TStack;
- begin
- Stack := TStack.Create();
- ContinueCycle := true;
- i := 1;
- while((i < Length(Str)) and ContinueCycle) do
- begin
- Curr := Str[i];
- if(Curr = '(') then
- Stack.Push(Pointer(Curr))
- else if(curr = ')') then
- begin
- if(Stack.Count = 0) then
- ContinueCycle := false
- else
- Stack.Pop();
- end;
- Inc(i);
- end;
- IsBalanced := ContinueCycle;
- end;
- function IsStringContainsParentheses(Str: String): Boolean;
- begin
- IsStringContainsParentheses := (Pos('(', Str) <> 0) or (Pos(')', Str) <> 0);
- end;
- function ReadFile(FilePath: String): String;
- var
- Str: String;
- InputFile: TextFile;
- begin
- Str := '';
- if(FileExists(FilePath)) then
- begin
- AssignFile(InputFile, FilePath);
- Reset(InputFile);
- if(Not Eof(InputFile)) then
- Readln(InputFile, Str);
- CloseFile(InputFile);
- end;
- ReadFile := Str;
- end;
- procedure SaveResult(ResultStr: String);
- var
- Decision: String;
- OutputFile: TextFile;
- begin
- while((Decision <> 'Y') and (Decision <> 'N')) do
- begin
- Writeln('Сохранить результат в файл? (Y - сохранить, N - не сохранять)');
- Readln(Decision);
- end;
- if(Decision = 'Y') then
- begin
- try
- AssignFile(OutputFile, 'output.txt');
- Rewrite(OutputFile);
- Writeln(OutputFile, ResultStr);
- CloseFile(OutputFile);
- Writeln('Результат сохранен в файл output.txt');
- except
- Writeln('Произошла ошибка при сохранении файла');
- end;
- end;
- end;
- procedure Main();
- var
- InputType, ResultStr, Str, FilePath: String;
- Res: Boolean;
- begin
- Writeln('Данная программа проверяет баланс скобок в строке');
- Writeln;
- while((InputType <> 'C') and (InputType <> 'F')) do
- begin
- Writeln('Введите C, если хотите ввести строку из консоли, или F, если хотите ввести строку из файла');
- Readln(InputType);
- end;
- if(InputType = 'C') then
- begin
- Writeln('Введите строку, для которой необходимо проверить баланс скобок');
- Readln(Str);
- end
- else if (InputType = 'F') then
- begin
- Writeln('Введите путь к файлу');
- Readln(FilePath);
- Str := ReadFile(FilePath);
- end;
- Res := IsStringContainsParentheses(Str);
- if(Res) then
- begin
- Res := IsBalanced(Str);
- if(Res) then
- ResultStr := 'Баланс скобок соблюдён'
- else
- ResultStr := 'Баланс скобок не соблюдён'
- end
- else
- ResultStr := 'В строке отсутсвуют скобки';
- Writeln(ResultStr);
- SaveResult(ResultStr);
- Readln;
- end;
- begin
- Main();
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement