thoga31 Posted June 4, 2014 at 10:48 PM Report #558255 Posted June 4, 2014 at 10:48 PM Bom, vamos lá tirar o pó ao quadro com algo simples mas útil para quem programa em consola 😉 Já aconteceu estarmos a querer ler um número e o utilizador introduz um valor alfanumérico. Resultado: o programa crasha. Podemos tratar a excepção com uma estrutura try-except. No entanto, não acho propriamente elegante. Portanto, deixo aqui um pequeno excerto de uma unit que tenho implementada há c'anos. A partir desta amostra poderão acrescentar com muito mais tipos de dados e novas funcionalidades. Aqui fica o código da unit e do programa de teste: USecRead.pas {$mode objfpc} unit USecRead; interface uses sysutils; type TSecureRead = class(TObject) private var vErrorPos : word; public function TLongint(const PROMPT : string; var i : longint) : boolean; function TReal(const PROMPT : string; var r : real) : boolean; property ErrorPos : word read vErrorPos; end; var SecureRead : TSecureRead; implementation function TSecureRead.TLongint(const PROMPT : string; var i : longint) : boolean; var s : string; e : word; begin Write(PROMPT); ReadLn(s); Val(s, i, e); TLongint := (e = 0); self.vErrorPos := e; end; function TSecureRead.TReal(const PROMPT : string; var r : real) : boolean; // DIY end; initialization SecureRead := TSecureRead.Create; finalization SecureRead.Free; end. USecRead_test.pas program USecRead_test; uses USecRead; const CRLF = #13+#10; var n : longint; begin repeat while not SecureRead.TLongint('n? ', n) do WriteLn('[KO] Nao foi lido um Longint!', CRLF, ' * Erro na posicao ', SecureRead.ErrorPos, CRLF, ' * Por curiosiade, n=', n, CRLF); Writeln('[OK] Longint lido correctamente!', CRLF, ' * n=', n); until n=0; end. E aqui um teste no Ubuntu: $ ./USecRead_test n? 123e5 [KO] Nao foi lido um Longint! * Erro na posicao 4 * Por curiosiade, n=0 n? 12345 [OK] Longint lido correctamente! * n=12345 n? 0 [OK] Longint lido correctamente! * n=0 $ 1 Report Knowledge is free!
nelson27 Posted January 15, 2018 at 05:56 PM Report #608954 Posted January 15, 2018 at 05:56 PM Agradecido
thoga31 Posted January 15, 2018 at 11:51 PM Author Report #608964 Posted January 15, 2018 at 11:51 PM @nelson27, este código já é antigo. Pode ser seriamente melhorado. Fica o desafio 🙂 Cumprimentos, thoga31. Knowledge is free!
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now