segunda-feira, 25 de fevereiro de 2019

C++ builder - Calculando médias em struct

As colunas e as linhas do StringGrid
foram carregadas com os membros da struct Escola.
Cada coluna do tipo float equivale
as notas obtidas pelo desempenho
de quatro alunos de uma determinada escola.
Mas o que queremos mesmos é saber a média
obtida por cada um dos quatros alunos
que prestaram exames do ensino médio.
Na varredura do laço for, as quatros
variáveis globais do tipo float,
recebem as cargas das variáveis membros
de struct Escola, e por serem globais,
ficou fácil trabalhar com elas dentro
dos métodos dos 4 RadioButton.



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

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include <string.h>
#include <conio.h>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1 ( TComponent* Owner ) :
TForm ( Owner ) {
}
float media;
float res_1 = 0, res_2 = 0, res_3 = 0, res_4 = 0;
struct Escola {
char *materias;
float notas_1;
float notas_2;
float notas_3;
float notas_4;
};
Escola Alunos [ 4 ] =
        {{"Ciências Humanas e Suas Tecnologias     ", 8.5, 6.8, 5.6, 7.5 },
{ "Ciências da Natureza e suas Tecnologias ", 9.5, 5.3, 5.8, 8.9 },
{ "Linguagens e Códigos e suas Tecnologias ", 8.6, 6.4, 8.1, 9.3 },
{ "Matemática e suas Tecnologias           ", 9.7, 6.5, 5.1, 7.2 }};
void __fastcall TForm1::RadioButton1Click ( TObject *Sender ) {
Canvas -> Font -> Size = 11;
Canvas -> Font -> Name = "arial";
Canvas -> Font -> Color = clBlue;
media = res_1 / 4;
if ( media < 7 ) {
Beep ( 1000, 500 );
//Removendo caracteres a direita da String
AnsiString media_1 = String ( media );
media_1.Delete ( 5, 15 );
Canvas -> TextOut( 50, 197, "Reprovado");
Canvas -> TextOut( 50, 217, "Média" );
Canvas -> Font -> Color = clRed;
//Impressão após a remoção
Canvas -> TextOut( 90, 217, " " + media_1 );
}
if ( media >= 7 ) {
//Removendo caracteres a direita da String
AnsiString media_1 = String ( media );
media_1.Delete ( 5, 15 );
Canvas -> TextOut( 50, 197, "Aprovado");
Canvas -> TextOut( 50, 217, "Média" );
Canvas -> Font -> Color = clRed;
//Impressão após a remoção
Canvas -> TextOut( 90, 217, " " + media_1 );
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::RadioButton2Click ( TObject *Sender ) {
Canvas -> Font -> Size = 11;
Canvas -> Font -> Name = "arial";
Canvas -> Font -> Color = clBlue;
media = res_2 / 4;
if ( media < 7 ) {
Beep ( 1000, 500 );
//Removendo caracteres a direita da String
AnsiString media_1 = String ( media );
media_1.Delete ( 5, 15 );
Canvas -> TextOut( 192, 197, "Reprovado");
Canvas -> TextOut( 192, 217, "Média" );
Canvas -> Font -> Color = clRed;
//Impressão após a remoção
Canvas -> TextOut( 232, 217, " " + media_1 );
}
if ( media >= 7 ) {
//Removendo caracteres a direita da String
AnsiString media_1 = String ( media );
media_1.Delete ( 5, 15 );
Canvas -> TextOut( 192, 197, "Aprovado");
Canvas -> TextOut( 192, 217, "Média" );
Canvas -> Font -> Color = clRed;
//Impressão após a remoção
Canvas -> TextOut( 232, 217, " " + media_1 );
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::RadioButton3Click ( TObject *Sender ) {
Canvas -> Font -> Size = 11;
Canvas -> Font -> Name = "arial";
Canvas -> Font -> Color = clBlue;
media = res_3 / 4;
if ( media < 7 ) {
Beep ( 1000, 500 );
//Removendo caracteres a direita da String
AnsiString media_1 = String ( media );
media_1.Delete ( 5, 15 );
Canvas -> TextOut( 336, 197, "Reprovado");
Canvas -> TextOut( 336, 217, "Média" );
Canvas -> Font -> Color = clRed;
//Impressão após a remoção
Canvas -> TextOut( 376, 217, " " + media_1 );
}
if ( media >= 7 ) {
//Removendo caracteres a direita da String
AnsiString media_1 = String ( media );
media_1.Delete ( 5, 15 );
Canvas -> TextOut( 336, 197, "Aprovado");
Canvas -> TextOut( 336, 217, "Média" );
Canvas -> Font -> Color = clRed;
//Impressão após a remoção
Canvas -> TextOut( 376, 217, " " + media_1 );
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::RadioButton4Click ( TObject *Sender ) {
Canvas -> Font -> Size = 11;
Canvas -> Font -> Name = "arial";
Canvas -> Font -> Color = clBlue;
media = res_4 / 4;
if ( media < 7 ) {
Beep ( 1000, 500 );
//Removendo caracteres a direita da String
AnsiString media_1 = String ( media );
media_1.Delete ( 5, 15 );
Canvas -> TextOut( 480, 197, "Reprovado");
Canvas -> TextOut( 480, 217, "Média" );
Canvas -> Font -> Color = clRed;
//Impressão após a remoção
Canvas -> TextOut( 232, 217, " " + media_1 );
}
if ( media >= 7 ) {
//Removendo caracteres a direita da String
AnsiString media_1 = String ( media );
media_1.Delete ( 5, 15 );
Canvas -> TextOut( 480, 197, "Aprovado");
Canvas -> TextOut( 480, 217, "Média" );
Canvas -> Font -> Color = clRed;
//Impressão após a remoção
Canvas -> TextOut( 520, 217, " " + media_1 );
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::RadioButton5Click ( TObject *Sender )
{
Canvas -> Font -> Size = 13;
Canvas -> Font -> Name = "arial";
Canvas -> Font -> Color = clRed;
Canvas -> TextOut( 280, 265, "Samuel Lima");
}
//---------------------------------------------------------------------------
void __fastcall TForm1::OnCreate ( TObject *Sender ) {
Label1 -> Left = 120;
Label1 -> Top = 15;
Label1 -> Caption = "C++ BUILDER - CALCULANDO MÉDIAS EM STRUCT ";
Label2 -> Left = 30;
Label2 -> Top = 45;
Label2 -> Caption = "    Ord                        Matérias                              AL1 AL2 AL3 AL4";
int a = 0, i;
StringGrid1 -> ColWidths [ 0 ] = 30;
StringGrid1 -> ColWidths [ 1 ] = 320;
StringGrid1 -> ColWidths [ 2 ] = 30;
StringGrid1 -> ColWidths [ 3 ] = 30;
StringGrid1 -> ColWidths [ 4 ] = 30;
StringGrid1 -> ColWidths [ 5 ] = 30;
for ( i = 0; i < 4; i++ ) {
a++;
StringGrid1 -> Cells [ 0 ] [ i ] = a;
StringGrid1 -> Cells [ 1 ] [ i ] = Alunos [ i ].materias;
StringGrid1 -> Cells [ 2 ] [ i ] = Alunos [ i ].notas_1;
StringGrid1 -> Cells [ 3 ] [ i ] = Alunos [ i ].notas_2;
StringGrid1 -> Cells [ 4 ] [ i ] = Alunos [ i ].notas_3;
StringGrid1 -> Cells [ 5 ] [ i ] = Alunos [ i ].notas_4;
res_1 = res_1 + Alunos [ i ].notas_1;
res_2 = res_2 + Alunos [ i ].notas_2;
res_3 = res_3 + Alunos [ i ].notas_3;
res_4 = res_4 + Alunos [ i ].notas_4;
}
}

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


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

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.Grids.hpp>
#include <Vcl.ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TStringGrid *StringGrid1;
TRadioButton *RadioButton1;
TRadioButton *RadioButton2;
TRadioButton *RadioButton3;
TRadioButton *RadioButton4;
TShape *Shape1;
TLabel *Label1;
TLabel *Label2;
TRadioButton *RadioButton5;
void __fastcall OnCreate(TObject *Sender);
void __fastcall RadioButton1Click(TObject *Sender);
void __fastcall RadioButton2Click(TObject *Sender);
void __fastcall RadioButton3Click(TObject *Sender);
void __fastcall RadioButton4Click(TObject *Sender);
void __fastcall RadioButton5Click(TObject *Sender);

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

object Form1: TForm1
  Left = 439
  Top = 165
  Caption = 'C++ BUILDER - CALCULANDO M'#201'DIAS EM STRUCT'
  ClientHeight = 300
  ClientWidth = 600
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clRed
  Font.Height = 0
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnCreate = OnCreate
  PixelsPerInch = 96
  TextHeight = 19
  object Shape1: TShape
    Left = 0
    Top = 0
    Width = 601
    Height = 297
    Brush.Color = clCream
    Pen.Width = 10
  end
  object Label2: TLabel
    Left = 0
    Top = 0
    Width = 5
    Height = 19
    Caption = ' '
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clBlack
    Font.Height = 0
    Font.Name = 'Tahoma'
    Font.Style = [fsBold]
    ParentFont = False
  end
  object Label1: TLabel
    Left = 0
    Top = 0
    Width = 5
    Height = 19
    Caption = ' '
  end
  object StringGrid1: TStringGrid
    Left = 48
    Top = 72
    Width = 505
    Height = 121
    BevelWidth = 3
    Color = clBlack
    ColCount = 6
    DefaultColWidth = 24
    FixedColor = clRed
    FixedCols = 0
    RowCount = 4
    FixedRows = 0
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clBlack
    Font.Height = -17
    Font.Name = 'Tahoma'
    Font.Style = []
    GradientEndColor = clBlack
    GradientStartColor = clBlack
    GridLineWidth = 5
    Options = [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect, goThumbTracking]
    ParentFont = False
    TabOrder = 0
    ColWidths = (
      24
      24
      24
      24
      24
      24)
  end
  object RadioButton1: TRadioButton
    Left = 48
    Top = 240
    Width = 73
    Height = 17
    Caption = 'Aluno 1'
    TabOrder = 1
    OnClick = RadioButton1Click
  end
  object RadioButton2: TRadioButton
    Left = 192
    Top = 240
    Width = 73
    Height = 17
    Caption = 'Aluno 2'
    TabOrder = 2
    OnClick = RadioButton2Click
  end
  object RadioButton3: TRadioButton
    Left = 336
    Top = 240
    Width = 73
    Height = 17
    Caption = 'Aluno 3'
    TabOrder = 3
    OnClick = RadioButton3Click
  end
  object RadioButton4: TRadioButton
    Left = 480
    Top = 240
    Width = 73
    Height = 17
    Caption = 'Aluno 4'
    TabOrder = 4
    OnClick = RadioButton4Click
  end
  object RadioButton5: TRadioButton
    Left = 224
    Top = 264
    Width = 49
    Height = 17
    Caption = 'Por:'
    TabOrder = 5
    OnClick = RadioButton5Click
  end
end


sexta-feira, 22 de fevereiro de 2019

C++ builder - de metro para centímetros

Quando declaramos uma classe em C++,
por definição ela é privada,
isto significa que não podemos acessar,
nem suas variáveis membros,
nem suas funções membros através de outras
funções que não seja também membro da classe.
Uma classe pode possuir tantos membros privados
como públicos, isto é um modo de conseguirmos
encapsular os seus membros e funções,
para que determinados itens não sejam acessados
por outras funções que não convém.
Para tornar partes de uma classe públicas,
isto é, acessíveis a outras partes do seu programa,
você deve declará-las após a palavra reservada public.
Todas as variáveis ou funções definidas depois de public
estão disponíveis a todas as outras funções no programa.
Para mostrar na prática o uso de classes em C++,
declarei a classe Convert_Metros_Centimetro,
que está ápta a converter metros em centímetros.
Tanto para o valor inserido como para o lido,
foram utilizados dois objetos TEdit do C++ Builder.


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

#include <vcl.h>
#pragma hdrstop

#include "OnPaint.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//Declarando uma classe de nome: Convert_Metros_Centimetro
class Convert_Metros_Centimetro {
//Tornando as variáveis membros públicas
public:
const static int METRO = 1;
const static int CENTIMETRO = METRO * 100;
/*========================================================================*/
//Por fazer parte da classe Convert_Metros_Centimetro
//Dizemos que esta é uma função membro
int converter ( int metro, int centimetro ) {
return ( metro * centimetro );
}
};
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1 ( TComponent* Owner ) :
TForm ( Owner ) {
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 230, 250, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 280, 250, "Samuel Lima" );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::OnPaint ( TObject *Sender ) {
Canvas -> Pen -> Width = 10;
Canvas -> Rectangle ( 05, 05, 595, 295 );
Canvas -> Font -> Size = 16;
Canvas -> Font -> Name = "alarm clock";
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 80, 20, "C++ BUILDER - DE METRO PARA CENTIMETRO" );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click ( TObject *Sender ) {
Canvas -> Font -> Name = "Cosolas";
//Criando o objeto conv do tipo Convert_Metros_Centimetro
Convert_Metros_Centimetro conv;
int x = Edit1 -> Text.ToIntDef ( 0 );
int conversor = conv.converter ( x, conv.CENTIMETRO );
if ( x > 0 ) {
Edit2 -> Text = conversor;
} else {
Edit2 -> Clear ( );
}
Edit1 -> SetFocus ( );
Informe ( Sender );
}
//---------------------------------------------------------------------------

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

#ifndef OnPaintH
#define OnPaintH
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TEdit *Edit1;
TEdit *Edit2;
TButton *Button1;
TLabel *Label1;
TLabel *Label2;
void __fastcall OnPaint(TObject *Sender);
void __fastcall Button1Click(TObject *Sender);
    void __fastcall Informe ( TObject *Sender );
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

object Form1: TForm1
  Left = 342
  Top = 219
  Width = 616
  Height = 338
  AutoScroll = True
  Caption = 'C++ BUILDER - CONVERSOR DE UNIDADE METRICA'
  Color = clSkyBlue
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnPaint = OnPaint
  PixelsPerInch = 96
  TextHeight = 13
  object Label1: TLabel
    Left = 176
    Top = 114
    Width = 50
    Height = 13
    Caption = 'Metro ( s )'
  end
  object Label2: TLabel
    Left = 376
    Top = 114
    Width = 75
    Height = 13
    Caption = 'Cent'#237'metro ( s )'
  end
  object Edit1: TEdit
    Left = 144
    Top = 133
    Width = 121
    Height = 28
    Color = clOlive
    Font.Charset = ANSI_CHARSET
    Font.Color = clWindowText
    Font.Height = -19
    Font.Name = 'alarm clock'
    Font.Style = []
    ParentFont = False
    TabOrder = 0
  end
  object Edit2: TEdit
    Left = 352
    Top = 133
    Width = 121
    Height = 28
    Color = clOlive
    Font.Charset = ANSI_CHARSET
    Font.Color = clWindowText
    Font.Height = -19
    Font.Name = 'alarm clock'
    Font.Style = []
    ParentFont = False
    TabOrder = 1
  end
  object Button1: TButton
    Left = 288
    Top = 136
    Width = 42
    Height = 25
    Caption = 'Ok'
    TabOrder = 2
    OnClick = Button1Click
  end
end

quarta-feira, 13 de fevereiro de 2019

C++ builder - vetor de struct em StringGrid

Se precisácemos criar grades  manualmente
precisariamos utilizar linhas horizontais
e verticais, mas o StringGrid já vem pronto,
só temos que alterar suas propriedades para
escolhermos o total de linhas e de colunas
que precisamos, para isto não há regras,
não existe um padrão definido,
tudo o que temos que fazer é adaptá-lo as
nessecidades de nosso projeto.
O StringGrid é muito usado para exibir
valores por categorias sem importar o tipo,
que é o nosso caso estamos preenchendo as grades
com os membros de uma struct previamente declarada.
Mas também pode ser usado em tabelas, planilhas,
ou onde separadores verticais e horizontais
forem necessários.
Aqui está mais um exemplo de utilização do StringGrid.





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

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
struct Escola {
char *nomes;
int idade;
float notas;
};

//---------------------------------------------------------------------------
void __fastcall TForm1::OnPaint(TObject *Sender)
{
  Label1 -> Caption = "C++ BUILDER - VETOR DE STRUCT EM STRINGGRID ";
Canvas -> Pen -> Color = clBlue;
Canvas -> Pen -> Width = 10;
Canvas -> Rectangle ( 05, 05, 590, 295 );

int i, j = 0;
struct Escola Alunos [ 10 ] =
{ { "Ana Celia    ", 19, 10.0},
{ "Eder Costa     ", 21, 9.9 },
{ "Humberto Gomes ", 18, 9.7 },
{ "Dijalma Lacerda", 22, 7.3 },
{ "Caroline Silva ", 18, 9.3 },
{ "Igor Goncalves ", 21, 8.6 },
{ "Bruna Carla    ", 19, 8.9 },
{ "Fabio Quadros  ", 22, 7.7 },
{ "Geany Barros   ", 19, 8.4 },
{ "Jaqueline Vega ", 22, 7.5}};
StringGrid1 -> ColWidths [ 0 ] = 30;
StringGrid1 -> ColWidths [ 1 ] = 25;
StringGrid1 -> ColWidths [ 2 ] = 150;
StringGrid1 -> ColWidths [ 4 ] = 30;
StringGrid1 -> ColWidths [ 6 ] = 30;
for ( i = 0; i < 10 ; i++ ) {
j++;
StringGrid1 -> Cells [ 0 ] [ i ] = j;
StringGrid1 -> Cells [ 2 ] [ i ] = Alunos [ i ].nomes;
StringGrid1 -> Cells [ 4 ] [ i ] = Alunos [ i ].idade;
StringGrid1 -> Cells [ 6 ] [ i ] = Alunos [ i ].notas;
}
Canvas -> Font -> Name = "Verdana";
Canvas -> Font -> Size = 18;
Canvas -> Font -> Style = TFontStyles ( ) << fsBold << fsUnderline
   << fsItalic;
Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 200, 260, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 260, 260, "Samuel Lima" );
}
//---------------------------------------------------------------------------


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

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.Grids.hpp>
#include <Vcl.ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TStringGrid *StringGrid1;
TLabel *Label1;
TLabel *Label2;
void __fastcall OnPaint(TObject *Sender);

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

object Form1: TForm1
  Left = 439
  Top = 165
  Caption = 'C++ BUILDER - VETOR DE STRUCT EM STRINGGRID'
  ClientHeight = 300
  ClientWidth = 600
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clRed
  Font.Height = 0
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnPaint = OnPaint
  PixelsPerInch = 96
  TextHeight = 19
  object Label1: TLabel
    Left = 70
    Top = 8
    Width = 6
    Height = 23
    Alignment = taCenter
    Caption = ' '
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clRed
    Font.Height = -19
    Font.Name = 'Tahoma'
    Font.Style = [fsItalic, fsUnderline]
    ParentFont = False
  end
  object Label2: TLabel
    Left = 106
    Top = 39
    Width = 376
    Height = 19
    Caption = 'Ordem           Nomes                 Idades     Notas'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clBlack
    Font.Height = 0
    Font.Name = 'Tahoma'
    Font.Style = [fsBold]
    ParentFont = False
  end
  object StringGrid1: TStringGrid
    Left = 106
    Top = 64
    Width = 399
    Height = 193
    BevelWidth = 3
    Color = clBlack
    ColCount = 8
    DefaultColWidth = 24
    FixedColor = clRed
    FixedCols = 0
    RowCount = 10
    FixedRows = 0
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clBlack
    Font.Height = -17
    Font.Name = 'Tahoma'
    Font.Style = []
    GradientEndColor = clBlack
    GradientStartColor = clBlack
    GridLineWidth = 5
    Options = [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect, goThumbTracking]
    ParentFont = False
    TabOrder = 0
    ColWidths = (
      24
      24
      24
      24
      24
      24
      24
      24)
  end
end

segunda-feira, 11 de fevereiro de 2019

C++ builder - matriz de inteiro em StringGrid

Em poucos minutos escrevi este código,
que já rodava na minha cabeça, 
mas a intenção mesmo era de apresentar
este componente poderoso do C++ Builder,
o "StringGrid", que não se resume ao seu nome,
pelo contrário, é totalmente genérico
e aceita qualquer tipo de dados do C/C++.
Declarei um StringGrid de 64 células,
sendo de 8 linhas por 8 colunas que receberão
os 64 números inteiros que foram escritos
num arquivo de texto, este arquivo  criado 
é fechado por fclose (); e em seguida é aberto
para leitura, onde o mesmo preenche as grades
do nosso StringGrid.



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

#include <vcl.h>
#pragma hdrstop
#define tam 8
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate ( TObject *Sender ) {
FILE * arq;
if ( ( arq = fopen ( "C:\\Users\\Embarcadero\\Documents\\"
"Projetos C++ Builder\\OnPaint\\Matriz.txt", "w" ) ) == NULL ) {
ShowMessage ( "Não foi possível criar o arquivo " );
}
Label1 -> Caption = "C++ BUILDER - MATRIZ DE INTEIRO EM STRINGGRID ";
int i = 0, j = 0;
int A [ tam ] [ tam ];
for( i = 1; i <= tam * tam; i++ ) {
fprintf ( arq, "%d ", i );
}
fclose ( arq );
if ( ( arq = fopen ( "C:\\Users\\Embarcadero\\Documents\\"
"Projetos C++ Builder\\OnPaint\\Matriz.txt", "r" ) ) == NULL ) {
ShowMessage ( "Não foi possível abrir o arquivo " );
}
for ( i = 0; i < tam; i++ ) {
for ( j = 0; j < tam; j++ ) {
fscanf ( arq, "%d", &A [ i ] [ j ] );
StringGrid1 -> Cells [ j ] [ i ] = A [ i ] [ j ];
}
}
fclose ( arq );
}

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

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

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.Grids.hpp>
#include <Vcl.ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TStringGrid *StringGrid1;
TLabel *Label1;
TShape *Shape1;
void __fastcall FormCreate(TObject *Sender);

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

#endif


object Form1: TForm1
  Left = 439
  Top = 165
  Caption = 'C++ BUILDER - MATRIZ DE INTEIRO EM STRINGGRID'
  ClientHeight = 300
  ClientWidth = 600
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clRed
  Font.Height = 0
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 19
  object Label1: TLabel
    Left = 70
    Top = 8
    Width = 6
    Height = 23
    Alignment = taCenter
    Caption = ' '
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clRed
    Font.Height = -19
    Font.Name = 'Tahoma'
    Font.Style = [fsItalic, fsUnderline]
    ParentFont = False
  end
  object Shape1: TShape
    Left = 0
    Top = 0
    Width = 600
    Height = 300
    Brush.Style = bsClear
    Pen.Color = clAqua
    Pen.Width = 10
    Shape = stRoundRect
  end
  object StringGrid1: TStringGrid
    Left = 200
    Top = 40
    Width = 233
    Height = 233
    BevelWidth = 3
    Color = clBlack
    ColCount = 8
    DefaultColWidth = 24
    FixedCols = 0
    RowCount = 8
    FixedRows = 0
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clBlack
    Font.Height = -17
    Font.Name = 'Tahoma'
    Font.Style = []
    GridLineWidth = 5
    Options = [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect, goThumbTracking]
    ParentFont = False
    TabOrder = 0
  end

end

domingo, 10 de fevereiro de 2019

Lendo arquivo de texto - objeto Memo

Aqui está um exemplo de leitura de arquivo de texto,
utilizando o objeto Memo do C++ Builder..
O Memo possui diversas propriedades fundamentais,
e entre elas achei necessário ativar um Scroll vertical
e horizontal, além da font com o seu tamanho e cor
entre outras.
O arquivo tem 448 linhas, mas pode ser 
expandido para milhares de linhas.
A parte lógica do código foi feita em C, 
mas aceita adaptações para que se torne
totalmente em C++.







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

#include <vcl.h>
#pragma hdrstop
#define SI_ZE 450
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1 ( TComponent* Owner ) :
TForm ( Owner ) {
}
//---------------------------------------------------------------------------
void __fastcall TForm1::OnPaint ( TObject *Sender ) {
Canvas -> Font -> Size = 16;
Canvas -> Font -> Name = "Arial";
Canvas -> Pen -> Color = clRed;
Canvas -> Rectangle ( 05, 05, 590, 290 );
Canvas -> Pen -> Width = 10;
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 60, 12, "C++ BUILDER - LENDO UM ARQUIVO DE TEXTO" );
String str_1 = " ";
FILE *arq;
char **no_me;
no_me = ( char** ) malloc ( SI_ZE * sizeof ( char* ) );
int c = 0, i;
arq = fopen ( "C:\\Users\\Embarcadero\\Documents\\Projetos C++ Builder\\OnPaint\\"
"Poesias famosas.txt", "r+b" );
if ( arq == NULL ) {
printf ( "Problemas na abertura do arquivo " );
}
for ( i = 0; i < SI_ZE; i++ ) {
no_me [ i ] = ( char* ) malloc ( SI_ZE * sizeof ( char* ) / 3 );
fgets ( no_me [ i ], 80, arq );
str_1 += i;
str_1 += "  ";
str_1 += no_me [ i ];
}
Memo1 -> Text = Memo1 -> Text + AnsiString ( str_1 );
Memo1 -> SelStart = 0;
free ( no_me );
fclose ( arq );
}

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


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

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TMemo *Memo1;
void __fastcall OnPaint(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif


object Form1: TForm1
  Left = 484
  Top = 207
  Caption = 'C++ BUILDER - LENDO UM ARQUIVO DE TEXTO'
  ClientHeight = 300
  ClientWidth = 600
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnPaint = OnPaint
  PixelsPerInch = 96
  TextHeight = 13
  object Memo1: TMemo
    Left = 40
    Top = 48
    Width = 521
    Height = 225
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -19
    Font.Name = 'Tahoma'
    Font.Style = [fsItalic]
    ParentFont = False
    ScrollBars = ssBoth
    TabOrder = 0
  end
end



quarta-feira, 6 de fevereiro de 2019

C++ builder - criando e abrindo um novo Form

Levei muitas pedradas dos inimigos do java,
e o pior é que muitos comentam até do que
nada entendem,mas isto eu prefiro esquecer.
Resolvi programar um pouco em C++,
e minha IDE preferida para C++ orientado a objetos
é o Rad Studio da Embarcadero,
e a versão que estou usando é a 10.2.2.
Neste prático exemplo indicado aos embarcaderos
estamos mostrando como criar uma barra de menu,
itens de menu, e também como abrir um novo Form,
e ainda como abrir imagens .png na tela do programa.







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

#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include "Unit2.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1( TComponent* Owner )
: TForm ( Owner )
{
pngPicture = new TPngImage;
mnuMain = new TMainMenu ( this );
mnuFile = new TMenuItem ( mnuMain );

mnuFileNew = new TMenuItem ( mnuFile );
mnuFileExit = new TMenuItem ( mnuFile );

mnuFile -> Caption = L"&Arq";
mnuFileNew -> Caption = L"&Form2";
mnuFileExit -> Caption = L"&Sair";

mnuFileNew -> OnClick = FileNewMenuClicked;
mnuFileExit -> OnClick = mnuFileExitClick;

mnuFile -> Add ( mnuFileNew );
mnuFile -> Add ( mnuFileExit );
mnuMain -> Items -> Add ( mnuFile );
}

//---------------------------------------------------------------------------
void __fastcall TForm1::Informe ( TObject *Sender ) {
Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 200, 200, "Por: " );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 250, 200, "Samuel Lima" );
Canvas -> Font -> Name = "Garamond";
Canvas -> Font -> Size = 20;
Canvas -> Font -> Color = clSkyBlue;
Canvas -> TextOut ( 200, 235, "MUITO OBRIGADO" );
SetBkMode ( Canvas->Handle, TRANSPARENT );
Canvas -> Font -> Color = clBlue;
Canvas -> TextOut ( 200, 229, "MUITO OBRIGADO" );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::OnPaint ( TObject *Sender )
{
Canvas -> Font -> Size = 18;
Canvas -> Font -> Name = "Garamond";
Canvas -> Font -> Color = clRed;
Canvas -> Pen -> Width = 10;
Canvas -> Pen -> Color = RGB ( 0, 255, 0 );
Canvas -> Rectangle ( 05, 05, 595, 275 );
SetTextColor ( Canvas -> Handle, RGB ( 255, 0,0 ) );
Canvas -> TextOut ( 80, 18, "CRIANDO E ABRINDO UM NOVO FORM" );
pngPicture->LoadFromFile("C:\\Users\\Embarcadero\\Documents\\"
"\\Projetos C++ Builder\\OnPaint\\Abrindo imagem com canvas\\10.2.2.png");
Canvas -> Draw ( 130, 40, pngPicture );
//delete BmpMercedes;
Informe ( Sender );
}

//---------------------------------------------------------------------------
void __fastcall TForm1::FileNewMenuClicked ( TObject *Sender )
{
Form1 -> Hide ( );
Form2 -> Show();
}

//---------------------------------------------------------------------------
void __fastcall TForm1::mnuFileExitClick ( TObject *Sender )
{
exit ( 0 );
}


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



#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.Menus.hpp>
#include <pngimage.hpp>
//---------------------------------------------------------------------------
enum PictureType { Bitmap, JPEG, GIF, PNG };
class TForm1 : public TForm
{
__published: // IDE-managed Components
void __fastcall OnPaint(TObject *Sender);

private: // User declarations
public: // User declarations    TMainMenu *mnuMain;
TPngImage         * pngPicture;
  TMainMenu *mnuMain;
TMenuItem *mnuFile;
TMenuItem *mnuFileNew;
TMenuItem *mnuFileExit;

void __fastcall FileNewMenuClicked ( TObject *Sender );
void __fastcall mnuFileExitClick ( TObject *Sender );
    void __fastcall Informe ( TObject *Sender );
__fastcall TForm1( TComponent* Owner );
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif


object Form1: TForm1
  Left = 342
  Top = 165
  Caption = 'Form1'
  ClientHeight = 300
  ClientWidth = 600
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnPaint = OnPaint
  PixelsPerInch = 96
  TextHeight = 13
end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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

#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include "Unit2.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2 *Form2;
//---------------------------------------------------------------------------
__fastcall TForm2::TForm2(TComponent* Owner)
: TForm(Owner)
{
pngPicture = new TPngImage;
mnuMain = new TMainMenu ( this );
mnuFile = new TMenuItem ( mnuMain );

mnuFileNew = new TMenuItem ( mnuFile );
mnuFileExit = new TMenuItem ( mnuFile );

mnuFile -> Caption = L"&Arq";
mnuFileNew -> Caption = L"&Form1";
mnuFileExit -> Caption = L"&Sair";

mnuFileNew -> OnClick = FileNewMenuClicked;
mnuFileExit -> OnClick = mnuFileExitClick;

mnuFile -> Add ( mnuFileNew );
mnuFile -> Add ( mnuFileExit );
mnuMain -> Items -> Add ( mnuFile );
}

 void __fastcall TForm2::OnPaint(TObject *Sender)
{
Canvas -> Font -> Size = 18;
Canvas -> Font->Name = "Garamond";
Canvas -> Pen -> Width = 10;
Canvas -> Pen -> Color = clRed;
Canvas -> Rectangle ( 05, 05, 595, 275 );
Canvas -> Font -> Color = clRed;
Canvas -> TextOut ( 80, 10, "CRIANDO E ABRINDO UM NOVO FORM" );
    pngPicture->LoadFromFile("C:\\Users\\Embarcadero\\Documents\\"
"\\Projetos C++ Builder\\OnPaint\\Abrindo imagem com canvas\\CX_1.png");
Canvas -> Draw ( 180, 30, pngPicture );
//delete BmpMercedes;
}
//---------------------------------------------------------------------------
void __fastcall TForm2::FileNewMenuClicked ( TObject *Sender )
{
Form2 -> Hide ( );
Form1 -> Show ( );
}

//---------------------------------------------------------------------------
void __fastcall TForm2::mnuFileExitClick ( TObject *Sender )
{
exit ( 0 );
}

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


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

#ifndef Unit2H
#define Unit2H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <pngimage.hpp>
//---------------------------------------------------------------------------

class TForm2 : public TForm
{
__published: // IDE-managed Components
void __fastcall OnPaint(TObject *Sender);
private: // User declarations
TPngImage         * pngPicture;
TMainMenu *mnuMain;
TMenuItem *mnuFile;
TMenuItem *mnuFileNew;
TMenuItem *mnuFileExit;

void __fastcall FormCreate ( TObject *Sender );
void __fastcall FileNewMenuClicked ( TObject *Sender );
void __fastcall mnuFileExitClick ( TObject *Sender );

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


object Form2: TForm2
  Left = 342
  Top = 165
  Caption = 'Form2'
  ClientHeight = 300
  ClientWidth = 600
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnPaint = OnPaint
  PixelsPerInch = 96
  TextHeight = 13
end

domingo, 3 de fevereiro de 2019

FMX - ordenando um vetor de struct

Aqui está um exemplo de como ordenar
um vetor de struct usando a função
qsort(); do C.
A parte lógica deste código pode ser
aproveitada po qualquer iniciante
de linguagem C, mas quem já conhece
o Embarcadero Rad Studio pode aproveitar
todo o código, para estudo.






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

#include <fmx.h>
#pragma hdrstop

#include "OnShow.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.fmx"
#define tam 20
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1 ( TComponent* Owner ) :
  TForm ( Owner ) {
}

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

typedef int ( *comp_unid ) ( const void* , const void* );
struct Nomes {
     int num;
char nomes [ 16 ];
};
struct Nomes vet_str [ 10 ] ={{10, "Jaqueline Vega" },
  { 5, "Eder Costa    " },
  { 8, "Humberto Gomes" },
  { 4, "Dijalma Lacerda"},
  { 3, "Caroline Silva" },
  { 9, "Igor Goncalves" },
  { 2, "Bruna Carla   " },
  { 6, "Fabio Quadros " },
  { 1, "Ana Celia     " },
  { 7, "Geany Barros " }};
int Qsort_ord ( struct Nomes *comp , struct Nomes *co_mp ) {
if ( comp -> num < co_mp -> num )
return -1;
else if ( comp -> num > co_mp -> num )
return 1;
else return 0;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::OnShow ( TObject *Sender ) {
Text1 -> Text = "C++ BUILDER - ORDENANDO UM VETOR DE STRUCT";
String str_1 = "";
String str_2 = "";
int i;
for ( i = 0; i < 10 ; i++ ) {
if ( i % 1 == 0 )
str_1 += "\n";
str_1 += vet_str [ i ].num;
str_1 += "   ";
str_1 += vet_str [ i ].nomes;
}
 Memo1 -> Text = Memo1 -> Text + AnsiString ( str_1 );
 Memo1 -> SelStart = 0;
 ShowMessage ( "Pressione o botão OK para\n ordenar o vetor de struct" );

 /*===========================================================================*/
  qsort ( ( void * ) &vet_str, 10, sizeof ( struct Nomes ), ( comp_unid ) Qsort_ord );
for ( i = 0; i < 10 ; i++ ) {
if ( i % 1 == 0 )
str_2 += "\n";
str_2 += vet_str [ i ].num;
str_2 += "   ";
str_2 += vet_str [ i ].nomes;
}
 Memo2 -> Text = Memo2 -> Text + AnsiString ( str_2 );
 Memo2 -> SelStart = 0;
Text2 -> Text = "Por: Samuel Lima";
}


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

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

#ifndef OnShowH
#define OnShowH
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <FMX.Controls.hpp>
#include <FMX.Forms.hpp>
#include <FMX.Objects.hpp>
#include <FMX.Types.hpp>
#include <FMX.Controls.Presentation.hpp>
#include <FMX.Memo.hpp>
#include <FMX.ScrollBox.hpp>
#include <FMX.StdCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
 TMemo *Memo1;
TMemo *Memo2;
TText *Text1;
TText *Text2;
TRectangle *Rectangle1;
TRectangle *Rectangle2;
TRectangle *Rectangle3;
 void __fastcall OnShow(TObject *Sender);


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


#endif


object Form1: TForm1
  Left = 341
  Top = 42
  Caption = 'C++ BUILDER - ORDENANDO UM VETOR DE STRUCT'
  ClientHeight = 300
  ClientWidth = 600
  Position = Designed
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  OnShow = OnShow
  Left = 341
  Top = 42
  DesignerMasterStyle = 0
  object Memo1: TMemo
    Touch.InteractiveGestures = [Pan, LongTap, DoubleTap]
    Caret.Color = claTurquoise
    DataDetectorTypes = []
    StyledSettings = [Family, FontColor]
    TextSettings.Font.Size = 14.000000000000000000
    TextSettings.Font.StyleExt = {00070000000200000004000000}
    TextSettings.WordWrap = True
    Position.X = 48.000000000000000000
    Position.Y = 40.000000000000000000
    Size.Width = 193.000000000000000000
    Size.Height = 225.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 3
    Viewport.Width = 189.000000000000000000
    Viewport.Height = 221.000000000000000000
  end
  object Memo2: TMemo
    Touch.InteractiveGestures = [Pan, LongTap, DoubleTap]
    DataDetectorTypes = []
    StyledSettings = [Family]
    TextSettings.Font.Size = 14.000000000000000000
    TextSettings.Font.StyleExt = {00070000000200000004000000}
    TextSettings.FontColor = claDarkblue
    TextSettings.WordWrap = True
    Position.X = 360.000000000000000000
    Position.Y = 40.000000000000000000
    Size.Width = 193.000000000000000000
    Size.Height = 225.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 2
    Viewport.Width = 189.000000000000000000
    Viewport.Height = 221.000000000000000000
  end
  object Text1: TText
    Position.X = 56.000000000000000000
    Position.Y = 8.000000000000000000
    Size.Width = 497.000000000000000000
    Size.Height = 25.000000000000000000
    Size.PlatformDefault = False
    TextSettings.Font.Size = 20.000000000000000000
    TextSettings.Font.StyleExt = {00040000000200000004000000}
    TextSettings.FontColor = claRed
  end
  object Text2: TText
    Position.X = 136.000000000000000000
    Position.Y = 264.000000000000000000
    Size.Width = 313.000000000000000000
    Size.Height = 25.000000000000000000
    Size.PlatformDefault = False
    TextSettings.Font.Size = 22.000000000000000000
    TextSettings.Font.StyleExt = {00040000000200000004000000}
    TextSettings.FontColor = claBlue
  end
  object Rectangle1: TRectangle
    Fill.Color = claNull
    Size.Width = 600.000000000000000000
    Size.Height = 300.000000000000000000
    Size.PlatformDefault = False
    Stroke.Color = claBlue
    Stroke.Thickness = 10.000000000000000000
  end
  object Rectangle2: TRectangle
    Fill.Color = claNull
    Position.X = 352.000000000000000000
    Position.Y = 40.000000000000000000
    Size.Width = 201.000000000000000000
    Size.Height = 225.000000000000000000
    Size.PlatformDefault = False
    Stroke.Color = claBlueviolet
    Stroke.Thickness = 5.000000000000000000
  end
  object Rectangle3: TRectangle
    Fill.Color = claNull
    Position.X = 40.000000000000000000
    Position.Y = 40.000000000000000000
    Size.Width = 193.000000000000000000
    Size.Height = 225.000000000000000000
    Size.PlatformDefault = False
    Stroke.Color = claDarkviolet
    Stroke.Thickness = 5.000000000000000000
  end
end

sábado, 2 de fevereiro de 2019

C++ builder - ordenando matriz de string

Declaramos e inicializamos uma matriz
bidimensional de string,
porém a mesma está toda desordenada,
Mas isto não é nenhum problema para
quem conhece a função Qsort () do C,
com apenas um click no botão da
caixa de de mensagem do C++ builder,
é possível ordená-la totalmente.








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

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
#include <time.h>
#define tam 10
int Qsort_Ord ( const void *a, const void *b ) {
return ( strcmp ( ( char * ) a, ( char * ) b ) );
}

//---------------------------------------------------------------------------
void __fastcall TForm1::OnPaint ( TObject *Sender ) {
char Nomes [ 10 ] [ 16 ] =
   {{"Jaqueline Vega "},
{"Eder Costa     "},
{"Humberto Gomes "},
{"Dijalma Lacerda"},
{"Caroline Silva "},
{"Igor Goncalves "},
{"Bruna Carla    "},
{"Fabio Quadros  "},
{"Ana Celia      "},
{"Geany Barros   "}};
Canvas -> Font -> Size = 16;
Canvas -> Font -> Name = "Arial";
Canvas->Brush->Color = static_cast <TColor> ( RGB ( 0, 191, 255 ) );
Canvas -> Pen -> Width = 10;
Canvas -> Rectangle ( 05, 05, 595, 295 );
SetTextColor ( Canvas->Handle, RGB ( 255, 25, 2 ) );
Canvas -> TextOut ( 60, 10, "C++ BUILDER - ORDENANDO MATRIZ DE STRING" );
int i;
Canvas -> Font -> Size = 12;
Canvas -> Font->Color = clBlack;
Canvas -> TextOut ( 60, 40, "Matriz desordenada" );
for ( i = 0; i < 10 ; i++ ) {
ListBox1 -> Items->Add ( Nomes [ i ] );
}
MessageDlgPos( L"Pressione o botão OK Para ordenar\n"
"A matriz bidimensional de string",
mtInformation, TMsgDlgButtons() << mbOK, 0, 290, 430 );
Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 400, 40, "Matriz ordenada" );
Canvas -> Font -> Color = clRed;
qsort ( ( void * ) Nomes , 10 , sizeof ( Nomes [ 0 ] ) , Qsort_Ord );
for ( i = 0; i < 10 ; i++ ) {
ListBox2 -> Items->Add ( Nomes [ i ] );
}
Canvas -> Font -> Size = 14;
Canvas -> Font -> Style = TFontStyles() << fsBold << fsUnderline << fsItalic ;
Canvas -> Font -> Color = clBlack;
Canvas -> TextOut ( 240, 260, "Por: Samuel Lima " );
}


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

#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
  TListBox *ListBox1;
  TListBox *ListBox2;
void __fastcall OnPaint(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif


object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'C++ BUILDER - ORDENANDO VETORES'
  ClientHeight = 300
  ClientWidth = 600
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnPaint = OnPaint
  PixelsPerInch = 96
  TextHeight = 13
  object ListBox1: TListBox
    Left = 24
    Top = 64
    Width = 217
    Height = 193
    Color = clAqua
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -16
    Font.Name = 'Tahoma'
    Font.Style = [fsItalic]
    ItemHeight = 19
    ParentFont = False
    TabOrder = 0
  end
  object ListBox2: TListBox
    Left = 352
    Top = 64
    Width = 217
    Height = 193
    Color = clLime
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clBlack
    Font.Height = -16
    Font.Name = 'Tahoma'
    Font.Style = [fsItalic]
    ItemHeight = 19
    ParentFont = False
    TabOrder = 1
  end
end