quinta-feira, 8 de outubro de 2020

Container multiset - declarando e inicializando


O container multiset que pertence ao arquivo
de cabeçalho <set>, tem muitas semelhanças,
ao seu parente set, do qual já falamos um pouco.
Acreditamos que a única diferença esteja
no seu recurso de suportar chaves duplicadas
na sua interface, enquanto um set não suporta.
Um multiset também é associativo,
e ordenado ascendente, mas não elimina
elementos duplicados.
Podemos remover ou inserir novos elementos
no container, automaticamente ele se ajusta
a uma ordem restrita referenciada por sua chave.
Como em um set, não se permite alterações de valores,
isto foi definido por segurança para que a ordem
dos elementos não fossem corrompidas.
Um programador iniciante em C++ fica confuso
na escolha do melhor repositório para seu programa,
isto ocorre pela semelhança, entre eles,
alguns com poucas diferenças em suas funções básicas.
Certamente encontraremos a estrutura correta
e adequada para nossos programas funcionarem 
com perfeição e com performance satisfatórias.
Mesmo os containers do C++ serem bastante flexíveis,
aceitando variadas conversões, é de extrema importância
evitar estes procedimentos, popularmente
chamado de gambiarra ou improvisos por nós programadores.
Para este exemplo, declaramos um multiset e um set.
O multiset foi inicializado com várias strings
em forma de frase, no seu próprio corpo bem desordenadas,
e na primeira impressão a da esquerda que se refere
ao multisete já notamos as frases todas ordenadas,
mas com todas as repetições, que é típico do multiset,
não exclui valores duplicados, e na impressão da direita,
que se refere ao set percebemos que os valores
repetidos foram apagados e as frases ficaram também
ordenadas como era de se esperar.




//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include <iterator>
#include <algorithm>
#include <set>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
    //SetBkColor ( Canvas -> Handle, RGB ( 255, 182, 193 ) );
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
    Canvas -> Font -> Size = 11;
    Canvas -> Font -> Name = "Arial";
    Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 350, 250, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 390, 250, "Samuel Lima" );
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 350, 265, "sa_sp10@hotmail.com" );
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Label_Manual ( TObject *Sender ) {
Label1 -> Visible = true;
Label1 -> Font -> Size = 12;
Label1 -> Font -> Name = "Arial";
Label1 -> Font-> Style = TFontStyles ( ) << fsBold << fsItalic;
//Label1 -> Font -> Color = clBlack;
Label1 -> Font -> Color = static_cast < TColor > ( RGB ( 0, 0, 0 ) );
Label1 -> Color = static_cast < TColor > ( RGB ( 255, 215, 0 ) );
Label1 -> Transparent = False;
Label1 -> Width = 240;
Label1 -> Height = 240;
Label1 -> Left = 40;
Label1 -> Top = 40;

Label2 -> Visible = true;
Label2 -> Font -> Size = 12;
Label2 -> Font -> Name = "Arial";
Label2 -> Font-> Style = TFontStyles ( ) << fsBold << fsItalic;
//Label2 -> Font -> Color = clBlack;
Label2 -> Font -> Color = static_cast < TColor > ( RGB ( 0, 0, 0 ) );
Label2 -> Color = static_cast < TColor > ( RGB ( 255, 255, 55 ) );
Label2 -> Transparent = False;
Label2 -> Width = 240;
Label2 -> Height = 240;
Label2 -> Left = 340;
Label2 -> Top = 40;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint ( TObject *Sender ) {
//Alterando a cor do form
Canvas -> Brush -> Color = static_cast < TColor > ( RGB ( 255, 255, 255 ) );
Canvas -> Font -> Size = 14;
Canvas -> Font-> Style = TFontStyles ( ) << fsBold << fsItalic;
Canvas -> Font -> Name = "Arial";
Canvas -> Pen -> Width = 10;
Canvas -> Pen -> Color = static_cast < TColor > ( RGB ( 255, 0, 0 ) );
Canvas -> RoundRect ( 05, 05, 595, 295, 25, 25 );
//Colorindo a cor de frente do canvas com RGB
SetTextColor ( Canvas -> Handle, RGB ( 255, 0, 0 ) );
//SetBkColor ( Canvas -> Handle, RGB ( 218, 112, 214 ) );
Canvas -> TextOut ( 100, 10, "MULTISET - DECLARANDO E INICIALIZANDO" );
Informe ( Sender );
   }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormShow ( TObject *Sender ) {
   Label_Manual ( Sender );
   String str_1;
   String str_2;

            std::multiset < String > mst = {
"  Goiaba vermelha, fruta boa  ",
"  Eu sabia fazer, mas esqueci ",
"  Fevereiro não tem carnaval  ",
"  Busque a paz e a siga       ",
"  Haverá paz no vale pra mim  ",
"  Cada louco com sua mania    ",
"  Amanhã será um novo dia     ",
"  Haverá paz no vale pra mim  ",
"  Goiaba vermelha, fruta boa  ",
"  Amanhã será um novo dia     ",
"  Eu sabia fazer, mas esqueci ",
"  Duvido que você irá desistir"};

for ( String val : mst ) {
   if ( val >= "  " )
str_1 += "\n";
str_1 += val;
}
Label1 -> Caption = str_1;

//Declarando um set para tipo String do C++ Builder
std::set < String > st;

//Copia os valores do multiset no set
for ( String val : mst ) {
st.insert ( val );
}

for ( String val : st ) {
   if ( val >= "  " )
str_2 += "\n";
str_2 += val;
}
Label2 -> Caption = str_2;


}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.Buttons.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TLabel *Label1;
TLabel *Label2;

void __fastcall Informe ( TObject *Sender );
void __fastcall Label_Manual ( TObject *Sender );
void __fastcall FormPaint ( TObject *Sender );
void __fastcall FormShow(TObject *Sender);
private: // User declarations

public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

terça-feira, 6 de outubro de 2020

Container set - declarando e inicializando


      Um set pode ser considerado semelhante
      a um recipiente ou um conjunto matemático.
      Por ser um repositório Associativo,
      jamais permite valores duplicados em sua interface,
      e os elementos são automaticamente ordenados
      de forma ascendente, eliminando duplicatas se houver.
      Um set só permite objetos de um mesmo tipo,
      que deve ser especificado no seu corpo em sua declaração.
      Uma vez armazenados, os objetos são do tipo key,
      que são chaves de valores constantes e que não se pode alterar.
      Se for preciso alterar um valor dentro de um set,
      precisamos primeiro excluir um elemento,
      para depois inserir outro em seu lugar,
      respeitando o tipo especificado no seu corpo.
      A parte teórica dos sets em C++ é um tanto extensa,
      mas não vejo nada mais necessário de apresentar,
      além do que já escrevemos aqui, mesmo porque
      o grau de dificuldade de usar os sets é quase 0,
      e isto é um privilégio para nós que estamos envolvidos com C++.
      No exemplo mostrado aqui, criamos um array do tipo string
      especial do C++ Builder, mas que poderia ser do tipo
      string padrão do C++, este array foi inicializado
      com algumas string em forma de frase, com algumas 
      repetidas e desordenadas.
      Na impressão da esquerda imprimimos o array
      como foi criado, e na impressão da direita
      temos o set imprimido com seus elementos
      ordenados e sem as frases repetidas do array de string. 



//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include <iterator>
#include <algorithm>
#include <set>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
   String texto [  ] = {
"  Goiaba vermelha, fruta boa    ",
"  Eu sabia fazer, mas esqueci   ",
"  Fevereiro não tem carnaval    ",
"  Busque a paz e a siga               ",
"  Haverá paz no vale pra mim    ",
"  Cada louco com sua mania      ",
"  Amanhã será um novo dia       ",
"  Haverá paz no vale pra mim    ",
"  Goiaba vermelha, fruta boa    ",
"  Amanhã será um novo dia       ",
"  Eu sabia fazer, mas esqueci   ",
"  Duvido que você irá desistir  " };
 //---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
    SetBkColor ( Canvas -> Handle, RGB ( 255, 182, 193 ) );
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
    Canvas -> Font -> Size = 11;
    Canvas -> Font -> Name = "Arial";
    Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 330, 250, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 370, 250, "Samuel Lima" );
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 330, 265, "sa_sp10@hotmail.com" );
}
 //---------------------------------------------------------------------------
 //---------------------------------------------------------------------------
void __fastcall TForm1::Label_Manual ( TObject *Sender ) {
Label1 -> Visible = true;
Label1 -> Font -> Size = 13;
Label1 -> Font -> Name = "Arial";
Label1 -> Font-> Style = TFontStyles ( ) << fsBold << fsItalic;
//Label1 -> Font -> Color = clBlack;
Label1 -> Font -> Color = static_cast < TColor > ( RGB ( 0, 0, 0 ) );
Label1 -> Color = static_cast < TColor > ( RGB ( 0, 255, 255 ) );
Label1 -> Transparent = False;
Label1 -> Width = 100;
Label1 -> Height = 70;
Label1 -> Left = 300;
Label1 -> Top = 40;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint ( TObject *Sender ) {
//Alterando a cor do form
Canvas -> Brush -> Color = static_cast < TColor > ( RGB ( 255, 255, 205 ) );
Canvas -> Font -> Size = 14;
Canvas -> Font-> Style = TFontStyles ( ) << fsBold << fsItalic;
Canvas -> Font -> Name = "Arial";
Canvas -> Pen -> Width = 10;
Canvas -> Pen -> Color = static_cast < TColor > ( RGB ( 205, 0, 205 ) );
Canvas -> RoundRect ( 05, 05, 595, 295, 25, 25 );
//Colorindo a cor de frente do canvas com RGB
SetTextColor ( Canvas -> Handle, RGB ( 0, 0, 0 ) );
SetBkColor ( Canvas -> Handle, RGB ( 0, 255, 103 ) );
Canvas -> TextOut ( 70, 15, "CONTAINER SET - DECLARANDO E INICIALIZANDO" );
int i, j;
int a = 20;
Canvas -> Font -> Size = 12;
  for ( i = 0; i < 12; i++ ) {
a = a + 20;
if ( texto [ i ] >= "  " ) {
   SetBkColor ( Canvas -> Handle, RGB ( 255, 255, 103 ) );
   Canvas -> TextOut ( 30, a, texto [ i ] );
}
  }

Informe ( Sender );
   }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormShow ( TObject *Sender ) {
   Label_Manual ( Sender );
   String str_1;

//Declarando set para tipo String do C++ Builder
std::set < String > st;

//Converte o array de string texto em set
for ( String val : texto ) {
st.insert ( val );
}

for ( String val : st ) {
   if ( val >= "  " )
str_1 += "\n";
str_1 += val;
}
Label1 -> Caption = str_1;
}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------


#ifndef Unit1H

#define Unit1H

//---------------------------------------------------------------------------

#include <System.Classes.hpp>

#include <Vcl.Controls.hpp>

#include <Vcl.StdCtrls.hpp>

#include <Vcl.Forms.hpp>

#include <Vcl.Buttons.hpp>

//---------------------------------------------------------------------------

class TForm1 : public TForm

{

__published: // IDE-managed Components

TLabel *Label1;


void __fastcall Informe ( TObject *Sender );

void __fastcall Label_Manual ( TObject *Sender );

void __fastcall FormPaint ( TObject *Sender );

void __fastcall FormShow(TObject *Sender);

private: // User declarations


public: // User declarations

__fastcall TForm1(TComponent* Owner);

};

//---------------------------------------------------------------------------

extern PACKAGE TForm1 *Form1;

//---------------------------------------------------------------------------

#endif 

quinta-feira, 1 de outubro de 2020

C++ builder - Array e o metodo random_shuffle


Logo no primeiro contato que tivemos
com o array do C++ observamos logo
que o mesmo não é tão diferente do
Array do C, apesar de possuir mais recursos,
e de possuir grande eficiência especialmente
para tamanhos pequenos, como os Arrays do C.
Estes arrays estão entre os vários
contêiner do C++ e possui tamanho fixo
especificado em tempo de execução.
São capazes de suportar iteradores
em acesso aleatórios, e possui alguns
métodos interessantes, que por enquanto
não vamos comentar exceto este que está
sendo usado pelo programa, a saber,
o método std::random_shuffle ( &a [ 0 ], &a [ 100 ] );
o método std::random_shuffle, trabalha organizando
seus elementos em base de troca,
cuidadosamente ele verifica quem vem primeiro
e quem vem depois, baseado no menor e no maior,
vai comparando e organizando aleatoriamente.
Me lembro que no início de nossa formação em C,
passávamos horas criando rotinas para embaralhar
elementos inteiros em Vetores e matrizes bidimensionais,
mas os estudantes de C++ tem o privilégio de usar
este poderoso método em seus programas com muita facilidade.




//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include <algorithm>//Para o  random_shuffle
#include <array>
#include <vector>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
int x;
bool y = false;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1 ( TComponent* Owner )
: TForm(Owner)
{
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
    SetBkColor ( Canvas -> Handle, RGB ( 255, 182, 193 ) );
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
Canvas -> Font -> Size = 11;
Canvas -> Font -> Name = "Arial";
Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 160, 250, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 200, 250, "Samuel Lima" );
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 160, 265, "sa_sp10@hotmail.com" );
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Label_Manual ( TObject *Sender ) {
Label1 -> Visible = true;
Label1 -> Font -> Size = 13;
Label1 -> Font -> Name = "Consolas";
Label1 -> Font-> Style = TFontStyles ( ) << fsBold;
Label1 -> Font -> Color = clBlack;
Label1 -> Width = 100;
Label1 -> Height = 70;
Label1 -> Left = 70;
Label1 -> Top = 30 ;

//Cria um botão persomalizado e com evento
//Foi declarado em Unit1.h
BitBtn1 = new TBitBtn ( Form1 );
BitBtn1 -> Parent = Form1;
BitBtn1 -> Font -> Size = 12;
BitBtn1 -> Width = 60;
BitBtn1 -> Height = 25;
BitBtn1 -> Left = 140;
BitBtn1 -> Top = 260;
BitBtn1 -> Font -> Color = clRed;
BitBtn1 -> Font -> Style = TFontStyles ( ) << fsBold << fsItalic;
BitBtn1 -> Caption = "shuffle";
BitBtn1 -> OnClick = FormShow;

//Cria mais um botão persomalizado e com evento
//Foi declarado em Unit1.h
BitBtn2 = new TBitBtn ( Form1 );
BitBtn2 -> Parent = Form1;
BitBtn2 -> Font -> Size = 12;
BitBtn2 -> Width = 60;
BitBtn2 -> Height = 25;
BitBtn2 -> Left = 410;
BitBtn2 -> Top = 260;
BitBtn2 -> Font -> Color = clRed;
BitBtn2 -> Font -> Style = TFontStyles ( ) << fsBold << fsItalic;
BitBtn2 -> Caption = "Fechar";
BitBtn2 -> OnClick = Fechar;

Memo1 = new TMemo ( Form1 );
Memo1 -> Parent = Form1;
Memo1 -> Lines -> Clear ( );
Memo1 -> Font -> Name = "Alarm clock";
Memo1 -> Font -> Size = 12;
Memo1 -> Font -> Color = static_cast < TColor > ( RGB ( 0, 0, 0 ) );
Memo1 -> Color = static_cast < TColor > ( RGB ( 240, 128, 128 ) );
Memo1 -> Font -> Style = TFontStyles ( ) << fsBold;
Memo1 -> BorderStyle = bsSingle;
Memo1 -> Width = 330;
Memo1 -> Height = 220;
Memo1 -> Enabled = true;
Memo1 -> Left = 140;
Memo1 -> Top = 35;
Memo1 -> ScrollBars = ssVertical;
//Memo1 -> WordWrap = true;

}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint ( TObject *Sender ) {
//Alterando a cor do form
Canvas -> Brush -> Color = static_cast < TColor > ( RGB ( 255, 255, 255 ) );
//Adiciona um fundo nos textos do canvas com RGB

Canvas -> Font -> Size = 14;
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
Canvas -> Font -> Name = "Arial";
Canvas -> Pen -> Width = 10;
Canvas -> Pen -> Color = static_cast < TColor > ( RGB ( 0, 0, 0 ) );
Canvas -> RoundRect ( 05, 05, 595, 295, 25, 25 );
//Colorindo a cor de frente do canvas com RGB
SetTextColor ( Canvas -> Handle, RGB ( 255, 0, 0 ) );
//SetBkColor ( Canvas -> Handle, RGB ( 0, 255, 103 ) );
Canvas -> TextOut ( 135, 10, "C++ - Array e o método random_shuffle" );
   }
//--------------------------------------------------------------------------
void __fastcall TForm1::FormShow ( TObject *Sender ) {
  Label_Manual ( Sender );

std::array < int, 100 > a; //Array do C++

String str_1;
int i;

String inf_0 ;
String inf_1;
String inf_2;

//Para o array do C ou o std::array do C++
for  ( i = 0; i < 100; i++ ) {
  a [ i ] = i;
}

  x++;

if ( x == 1 ) {
for ( i = 0; i < 30; i++ ) {
inf_0 += " ";
}
Memo1 -> Lines -> Strings [ 0 ] = inf_0;
for ( int val : a ) {
str_1 += " ";
if ( val >= 0 && val < 10 )
str_1 += ( "0" );
str_1 += val;
}
Memo1 -> Text = Memo1 -> Text + AnsiString ( str_1 );
}

if ( x == 2 ) {
    BitBtn1 -> Caption = "Sobre";
//Imita um dos sons do windows
//MessageBeep ( 0 );
//Embaralhando e imprimindo
std::random_shuffle ( &a [ 0 ], &a [ 100 ] );
//std::random_shuffle ( a.begin ( ), a.end ( ) );

for ( int val : a ) {
str_1 += " ";
if ( val >= 0 && val < 10 )
str_1 += ( "0" );
str_1 += val;
}
for ( i = 0; i < 30; i++ ) {
inf_0 += " ";
}
    Memo1 -> Color = static_cast < TColor > ( RGB ( 255, 140, 0 ) );
Memo1 -> Lines -> Strings [ 0 ] = inf_0;//255,140,0
Memo1 -> Text = Memo1 -> Text + AnsiString ( str_1 );
}
if ( x == 3 ) {
    BitBtn1 -> Caption = "Início";
Memo1 -> Font -> Name = "Arial";
Memo1 -> Font -> Size = 12;
Memo1 -> Font -> Color = static_cast < TColor > ( RGB ( 0, 0, 0 ) );
Memo1 -> Color = static_cast < TColor > ( RGB ( 0, 128, 128 ) );
Memo1 -> Font -> Style = TFontStyles ( ) << fsBold << fsItalic;

for ( i = 0; i < 500; i++ ) {
inf_0 += " ";
}
Memo1 -> Lines -> Strings [ 0 ] = inf_0;

inf_1 = "                  Por: Samuel Lima";
inf_2 = "                  sa_sp10@hotmail.com";

Memo1 -> Lines -> Add ( inf_1 );
Memo1 -> Lines -> Add ( inf_2 );
x = 0;
}
}
//---------------------------------------------------------------------------
 void __fastcall TForm1::Fechar ( TObject *Sender ) {
  Close ( );
 }
//--------------------------------------------------------------------------


//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.Buttons.hpp>
#include <Vcl.ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TLabel *Label1;

void __fastcall Informe ( TObject *Sender );
void __fastcall Label_Manual ( TObject *Sender );
void __fastcall FormPaint ( TObject *Sender );
void __fastcall FormShow ( TObject *Sender );
void __fastcall Fechar ( TObject *Sender );
private: // User declarations
  TBitBtn *BitBtn1;
  TBitBtn *BitBtn2;
   TMemo *Memo1;
public: // User declarations
__fastcall TForm1 ( TComponent* Owner );
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif



terça-feira, 8 de setembro de 2020

C++ builder - capturando coordenadas do form II

Aqui está um exemplo de como capturar
as coordenadas do form pelo movimento do mouse.
Neste aqui estamos utilisando o evento FormMouseMove,
no exemplo anterior, utilizamos o evento FormMouseDown.



Veja abaixo os códigos do programa

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
        Canvas -> Font -> Size = 11;
        Canvas -> Font -> Name = "Arial";
        Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 160, 250, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 200, 250, "Samuel Lima" );
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 160, 265, "sa_sp10@hotmail.com" );
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Label_Manual ( TObject *Sender ) {
Label1 -> Visible = true;
Label1 -> Font -> Size = 14;
Label1 -> Font -> Name = "alarm clock";
Label1 -> Font-> Style = TFontStyles ( ) << fsBold;
Label1 -> Font -> Color = clRed;
Label1 -> Width = 100;
Label1 -> Height = 70;
Label1 -> Left = 20;
Label1 -> Top = 50;

BitBtn1 -> Font -> Name = "Arial";
        BitBtn1 -> Visible = true;
        BitBtn1 -> Font -> Size = 12;
BitBtn1 -> Font-> Style = TFontStyles ( ) << fsItalic << fsBold;
        BitBtn1 -> Font -> Color = clBlack;
BitBtn1 -> Width = 50;
BitBtn1 -> Height = 22;
BitBtn1 -> Top = 260;
BitBtn1 -> Left = 520;
BitBtn1 -> Caption = ( "Sair" );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) {
Label1 -> Caption = StrToInt ( X );
Label1 -> Caption = Label1 -> Caption + "\n";
Label1 -> Caption = Label1 -> Caption + StrToInt ( Y );
}
//------------------------------------------------------------------------------
void __fastcall TForm1::FormShow ( TObject *Sender ) {
Label_Manual ( Sender );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint ( TObject *Sender ) {
//Alterando a cor do form
Canvas -> Brush -> Color = static_cast < TColor > ( RGB ( 255, 255, 205 ) );
//Adiciona um fundo nos textos do canvas com RGB
SetBkColor ( Canvas -> Handle, RGB ( 255, 182, 193 ) );
Canvas -> Font -> Size = 14;
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
Canvas -> Font -> Name = "Arial";
Canvas -> Pen -> Width = 10;
Canvas -> Pen -> Color = clRed;
Canvas -> RoundRect ( 05, 05, 595, 295, 25, 25 );
//Colorindo a cor de frente do canvas com RGB
SetTextColor ( Canvas -> Handle, RGB ( 0, 0, 0 ) );
Canvas -> TextOut ( 30, 15, "C++ BUILDER - CAPTURANDO COORDENADAS DO FORM" );
Informe ( Sender );
   }
   //---------------------------------------------------------------------------
void __fastcall TForm1::BitBtn1Click ( TObject *Sender ) {
Close ( );
}
//------------------------------------------------------------------------------


//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.Buttons.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TLabel *Label1;
TBitBtn *BitBtn1;
void __fastcall Label_Manual ( TObject *Sender );
    void __fastcall Informe ( TObject *Sender );
void __fastcall FormShow ( TObject *Sender );
void __fastcall FormPaint ( TObject *Sender );
void __fastcall BitBtn1Click ( TObject *Sender );
void __fastcall FormMouseMove ( TObject *Sender, TShiftState Shift, int X, int Y );

private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

C++ builder - capturando coordenadas do form

Aqui está um exemplo de como capturar
as coordenadas do form pelo click do mouse.
Aqui está um exemplo de como capturar
as coordenadas do form pelo movimento do mouse.
Neste aqui estamos utilisando o evento FormMouseMove,
no exemplo anterior, utilizamos o evento FormMouseDown.


Veja abaixo os códigos do programa

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
        Canvas -> Font -> Size = 11;
        Canvas -> Font -> Name = "Arial";
        Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 160, 250, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 200, 250, "Samuel Lima" );
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 160, 265, "sa_sp10@hotmail.com" );
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Label_Manual ( TObject *Sender ) {
Label1 -> Visible = true;
Label1 -> Font -> Size = 14;
Label1 -> Font -> Name = "alarm clock";
Label1 -> Font-> Style = TFontStyles ( ) << fsBold;
Label1 -> Font -> Color = clRed;
Label1 -> Width = 100;
Label1 -> Height = 70;
Label1 -> Left = 20;
Label1 -> Top = 50;

BitBtn1 -> Font -> Name = "Arial";
        BitBtn1 -> Visible = true;
        BitBtn1 -> Font -> Size = 12;
BitBtn1 -> Font-> Style = TFontStyles ( ) << fsItalic << fsBold;
        BitBtn1 -> Font -> Color = clBlack;
BitBtn1 -> Width = 50;
BitBtn1 -> Height = 22;
BitBtn1 -> Top = 260;
BitBtn1 -> Left = 520;
BitBtn1 -> Caption = ( "Sair" );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormMouseDown ( TObject *Sender, TMouseButton Button, TShiftState Shift,
  int X, int Y ) {
Label1 -> Caption = StrToInt ( X );
Label1 -> Caption = Label1 -> Caption + "\n";
Label1 -> Caption = Label1 -> Caption + StrToInt ( Y );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormShow ( TObject *Sender ) {
Label_Manual ( Sender );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint ( TObject *Sender ) {
//Alterando a cor do form
Canvas -> Brush -> Color = static_cast < TColor > ( RGB ( 255, 255, 205 ) );
//Adiciona um fundo nos textos do canvas com RGB
SetBkColor ( Canvas -> Handle, RGB ( 205, 255, 051 ) );
Canvas -> Font -> Size = 14;
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
Canvas -> Font -> Name = "Arial";
                 Canvas -> Pen -> Width = 10;
Canvas -> Pen -> Color = clBlue;
Canvas -> RoundRect ( 05, 05, 595, 295, 25, 25 );
//Colorindo a cor de frente do canvas com RGB
SetTextColor ( Canvas -> Handle, RGB ( 0, 0, 0 ) );
Canvas -> TextOut ( 30, 15, "C++ BUILDER - CAPTURANDO COORDENADAS DO FORM" );
Informe ( Sender );
   }
   //---------------------------------------------------------------------------
void __fastcall TForm1::BitBtn1Click ( TObject *Sender ) {
Close ( );
}
//------------------------------------------------------------------------------

C++ builder - Variáveis signed e unsigned

 Variáveis signed e unsigned significam ( com sinal e sem sinal ),
que são dois modificadores de tipos muito útil aos programadores,
desta importante linguagem.
A finalidade destes modificadores é de rejeitar
valores que não serão aceitos em nosso programa.
Os tipos inteiros e os ( char ), aceitam normalmente
valores negativos ou positivos,
mas se na declaração destes tipos for antecedido
com o modificador unsigned, só podemos fazer uso
de números iguais ou maiores que zero.
Programadores podem querer tentar atribuir valores
acima do que uma variável possa suportar,
já adiantamos que se uma variável for excedida,
sendo declarada com unsigned, seus valores
continuarão a partir do zero, até o máximo
que a variável possa suportar, e se chegar
no seu extremo voltará novamente para o zero.
mas se for do tipo modificador signed, 
seus valores serão armazendos,
a partir do menor valor negativo ( -1 ).
até o máximo que a variável possa suportar,
e se chegar no seu extremo voltará novamente para o zero.
Então nestas linhas aprendemos que uma variável unsigned,
não aceita valores negativos, e no exemplo passado aqui,
podemos ver isto com muita clareza.

Declaramos duas variáveis, e inicializamos as mesmas,
com o mesmo valor ( 10 ), uma do tipo char com unsigned,
cujos valores ficam restrito entre ( 0 e 255 ),
que é justamente o dobro dos valores máximos de uma variável
char sem sinal ( -128 a 127 ).
e a outra variável também do tipo char declarada
com signed ( com sinal ).
Assista agora atentamente este vídeo,
e acesse o link para apreciação do código,
não leve em conta as diversas linhas atribuída
a interface gráfica, sobrou um pouco de tempo
e a paciência foi a virtude fundamental para isto. 




Veja abaixo os códigos do programa:

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

unsigned char a = 10;
signed char b = 10;
bool x = false;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1 ( TComponent* Owner )
: TForm ( Owner )
{
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
        Canvas -> Font -> Size = 11;
        Canvas -> Font -> Name = "Arial";
        Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 160, 250, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 200, 250, "Samuel Lima" );
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 160, 265, "sa_sp10@hotmail.com" );
}
 //---------------------------------------------------------------------------
void __fastcall TForm1::Label_Manual ( TObject *Sender ) {
Label1 -> Visible = true;
        Label1 -> Font -> Size = 16;
Label1 -> Font -> Name = "alarm clock";
Label1 -> Font-> Style = TFontStyles ( ) << fsBold;
Label1 -> Font -> Color = clRed;
Label1 -> Width = 230;
Label1 -> Height = 20;
Label1 -> Left = 230;
Label1 -> Top = 69;

Label2 -> Visible = true;
Label2 -> Font -> Size = 16;
        Label2 -> Font -> Name = "alarm clock";
Label2 -> Font-> Style = TFontStyles ( ) << fsBold;
Label2 -> Font -> Color = clRed;
        Label2 -> Width = 230;
Label2 -> Height = 20;
Label2 -> Left = 230;
Label2 -> Top = 99;

BitBtn1 -> Font -> Name = "Venacti";
        BitBtn1 -> Visible = true;
        BitBtn1 -> Font -> Size = 12;
BitBtn1 -> Font-> Style = TFontStyles ( ) << fsItalic << fsBold;
        BitBtn1 -> Font -> Color = clBlack;
BitBtn1 -> Width = 50;
BitBtn1 -> Height = 22;
BitBtn1 -> Top = 260;
BitBtn1 -> Left = 70;
BitBtn1 -> Caption = ( "Stop" );

        BitBtn2 -> Font -> Name = "Venacti";
        BitBtn2 -> Font -> Size = 12;
BitBtn2 -> Font -> Color = clBlack;
BitBtn2 -> Font-> Style = TFontStyles ( ) << fsItalic ;
BitBtn2 -> Top = 260;
BitBtn2 -> Left = 480;
BitBtn2 -> Height = 22;
BitBtn2 -> Width = 50;
BitBtn2 -> Caption = ( "Run" );
}
//---------------------------------------------------------------------------
void Partida_Rapida ( void ) {
if ( a > 10 )
   Form1 -> Timer1 -> Interval = 100;
   Form1 -> Label1 -> Caption = a;
   a--;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::OnTimer ( TObject *Sender ) {
Label_Manual ( Sender );
if ( x == false ) {
Timer1 -> Interval = 0;
}
if ( x == true ) {
Timer1 -> Interval = 1000;
}
Label2 -> Caption = b;
if ( a < 10 )
Label1 -> Caption = a;

if ( a > 10 ) {
  Partida_Rapida ( );
}
a--;
b--;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BitBtn1Click ( TObject *Sender ) {
Timer1 -> Interval = 0;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BitBtn2Click ( TObject *Sender ) {
Timer1 -> Interval = 1000;
         x = true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormShow ( TObject *Sender ) {
Label_Manual ( Sender );
  Label1 -> Left = 230;
Label1 -> Caption =  a;

Label2 -> Left = 230;
Label2 -> Caption = StrToInt ( b );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint ( TObject *Sender ) {
Canvas -> Font -> Size = 14;
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
Canvas -> Font -> Name = "Arial";
                 Canvas -> Pen -> Width = 10;
Canvas -> Pen -> Color = clRed;
Canvas -> RoundRect ( 05, 05, 595, 295, 25, 25 );
SetTextColor ( Canvas -> Handle, RGB ( 255, 25, 2 ) );
Canvas -> TextOut ( 160, 10, "VARIÁVEIS SIGNED E UNSIGNED" );
Canvas -> Font -> Size = 12;
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 160, 35, "Observe o comportamento das variáveis" );

Canvas -> Font -> Size = 14;
Canvas -> Font-> Style = TFontStyles ( ) << fsItalic;
Canvas -> Font -> Name = "Arial";
Canvas -> Font -> Size = 12;
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 70, 70,  "Variável unsigned => " );
Canvas -> TextOut ( 70, 100, "Variável signed     => " );
Informe ( Sender );
}
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.ExtCtrls.hpp>
#include <Vcl.Buttons.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TTimer *Timer1;
TLabel *Label1;
TLabel *Label2;
TBitBtn *BitBtn1;
TBitBtn *BitBtn2;
void __fastcall OnTimer ( TObject *Sender );
void __fastcall Informe ( TObject *Sender );
void __fastcall Label_Manual ( TObject *Sender );
void __fastcall FormShow (TObject *Sender );
void __fastcall FormPaint ( TObject *Sender );
void __fastcall BitBtn1Click ( TObject *Sender );
void __fastcall BitBtn2Click ( TObject *Sender );
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

segunda-feira, 7 de setembro de 2020

STRCHR - Pesquisando caractere numa string

Esta função varre uma string na direção frontal
em busca da primeira ocorrência de um caractere.
strchr retorna um ponteiro para a primeira ocorrência
do caractere procurado na string,
se o caractere não ocorre na string, strchr retorna nulo.
Leve em conta o terminador nulo como parte da string.




Veja abaixo o código do programa:

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

void Janela ( ) {
int l, c;
for ( l = 1; l <= 30 ; l++ ) {
         for ( c = 1; c < 80 ; c++ ) {
              gotoxy ( c , l );
  if ( l == 2 ) {
   cprintf ( " " );
  }
  if ( c == 1 ) {
   cprintf ( "  " );
              }
              if ( c == 79 ) {
   textattr ( 200 );
   cprintf ( "  " );
  }
}
}
}
//------------------------------------------------------------------------------
void Pesq_Caractere ( char str [ 20 ], char c );
//------------------------------------------------------------------------------
void Informe ( ) {
         textcolor ( LIGHTBLUE );
gotoxy ( 26, 19 );
cprintf ( "Por: " );
textcolor ( LIGHTMAGENTA );
cprintf ( "Samuel Lima" );
         textcolor ( WHITE );
gotoxy ( 26, 20 );
cprintf ( "sa_sp10@hotmail.com" );
         Sleep ( 1800 );
textcolor ( LIGHTRED );
gotoxy ( 37, 23 );
cprintf ( "MUITO OBRIGADO" );
}
//------------------------------------------------------------------------------
void Digita_Caractere ( char str [ 20 ], char c ) {
system ( "cls" );
Janela ( );
textbackground ( BLACK );
textcolor ( LIGHTRED );
gotoxy ( 20 , 3 );
cprintf ( "STRCHR - PESQUISANDO CARACTERE NUMA STRING" );
textcolor ( LIGHTBLUE );
         gotoxy ( 28 , 5 );
cprintf ( "Digite uma Palavra : " );
         textcolor ( LIGHTRED );
         scanf ( "%s" , str );
         fflush ( stdin );
textcolor ( LIGHTBLUE );
         gotoxy ( 28 , 7 );
cprintf ( "Veja abaixo a Palavra digitada " );
         textcolor ( LIGHTRED );
         gotoxy ( 28 , 9 );
cprintf ( "%s" , str );
Sleep ( 1800 );
Pesq_Caractere ( str, c );
}
//------------------------------------------------------------------------------
void Pesq_Caractere ( char str [ 20 ] , char c ) {
char *pch;
int op;
do {
system ( "cls" );
Janela ( );
textbackground ( BLACK );
textcolor ( LIGHTRED );
gotoxy ( 20 , 3 );
cprintf ( "STRCHR - PESQUISANDO CARACTERE NUMA STRING" );
textcolor ( LIGHTBLUE );
gotoxy ( 28 , 5 );
cprintf ( "Digite um Caractere : " );
textcolor ( LIGHTRED );
scanf ( "%c" , &c );
fflush ( stdin );
pch = strchr ( str , c );
if ( pch != NULL ) {
         textcolor ( LIGHTBLUE );
gotoxy ( 18 , 7 );
cprintf ( "O Caractere " );
                 textcolor ( LIGHTRED );
cprintf ( "%c" , c );
textcolor ( LIGHTBLUE );
cprintf ( " foi encontrado na " );
                 textcolor ( LIGHTRED );
cprintf ( "%dª" , pch - str );
textcolor ( LIGHTBLUE );
cprintf ( " posição " );
                 textcolor ( LIGHTBLUE );
cprintf ( " da Palavra" );
Sleep ( 1800 );

textcolor ( LIGHTRED );
gotoxy ( 18, 11 );
cprintf ( "Escolha uma opção abaixo" );

textcolor ( LIGHTBLUE );
gotoxy ( 18, 13 );
cprintf ( "1 - Pesquisar outro caractere na mesma palavra" );

gotoxy ( 18, 15 );
cprintf ( "2 - Digitar outra palavra" );

gotoxy ( 18, 17 );
cprintf ( "3 - Finalizar o programa" );
                 Informe ( );
textcolor ( LIGHTRED );
                 gotoxy ( 43, 17 );
scanf ( "%d" , &op );
fflush ( stdin );

if ( op == 1 ) {
Pesq_Caractere ( str, c );
}
if ( op == 2 ) {
  Digita_Caractere ( str, c );
}
if ( op == 3 ) {
             exit ( 0 );
}
} else {
textcolor ( LIGHTBLUE );
                 gotoxy ( 18 , 13 );
cprintf ( "O Caractere " );
                 textcolor ( LIGHTRED );
cprintf ( "%c" , c );
                 textcolor ( LIGHTBLUE );
cprintf ( " não foi encontrado na Palavra" );
                 Sleep ( 1800 );
                 textcolor ( LIGHTBLUE );
                 gotoxy ( 28 , 15 );
                 cprintf ( "\aTente novamente" );
Sleep ( 1800 );
Pesq_Caractere ( str, c );
getche ( );
}
Sleep ( 1800 );
} while ( true );
}
//------------------------------------------------------------------------------
int main ( ) {
system ( "title STRCHR - PESQUISANDO CARACTERE NUMA STRING" );
char c;
char str [ 20 ];
Digita_Caractere ( str, c );
}
//------------------------------------------------------------------------------