quinta-feira, 26 de março de 2020

Casting de tipos - de char para inteiros

Em linguagem C, uma string é um vetor de caracteres,
e não podemos esquecer de reservar um a mais
no final da string que será o O terminador nulo.
O C, não possui um tipo de dados string,
ao contrário de outras linguagens,
mas isto para nós não representa nenhum problema,
basta declarar um vetor de caracteres,
ou seja um vetor do tipo char como o do exemplo
que estamos mostrando no momento,
ou seguindo a forma geral representada abaixo:
char nome_da_string [ tamanho ];
Embora estamos usando o C++ Builder para criação
da interface gráfica, preferi usar a declaração oficial
de uma string em C, obviamente neste caso
estamos usando um vetor bidimensional de caracteres,
com os 100 primeiros números naturais em string,
Os compiladores de linguagem C contêm funções
como atoi( ), atof( ) e atol( ) nas suas bibliotecas-padrões.
basicamente a finalidade , destas funções é  converter
uma string de dígitos em inteiros, float ou double,
e foi isto que fizemos,  utilizamos um casting
para converter de char para inteiros usando a função atoi,
e os resultados foram excelentes,
acompanhem primeiro no vídeo abaixo:




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

#include <vcl.h>
#pragma hdrstop

#define tam 100
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
    char Vet [ 100 ] [ 4 ] = { "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
            "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31",
            "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
            "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53",
            "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64",
            "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75",
            "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86",
            "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97",
            "98", "99", "100" };
    int i, j, Vetor = 0, Ve_tor [ 100 ];
//---------------------------------------------------------------------------
void __fastcall TForm1::Label_Manual ( TObject *Sender ) {
    Label1 -> Font -> Size = 12;
    Label1 -> Font-> Style = TFontStyles ( ) << fsItalic ;
    Label1 -> Font -> Color = clBlack;
    Label1 -> Width = 130;
    Label1 -> Height = 20;
    Label1 -> Left = 160;
    Label1 -> Top = 40;

    Label2 -> Font -> Size = 12;
    Label2 -> Font-> Style = TFontStyles ( ) << fsItalic ;
    Label2 -> Font -> Color = clBlue;
    Label2 -> Width = 130;
    Label2 -> Height = 20;
    Label2 -> Left = 160;
    Label2 -> Top = 40;

    Label3 -> Font -> Size = 12;
    Label3 -> Font-> Style = TFontStyles ( ) << fsItalic ;
    Label3 -> Font -> Color = clRed;
    Label3 -> Width = 130;
    Label3 -> Height = 20;
    Label3 -> Left = 160;
    Label3 -> Top = 40;

    BitBtn1 -> Visible = true;
    BitBtn1 -> Font -> Size = 12;
    BitBtn1 -> Font -> Color = clBlue;
    BitBtn1    -> Font-> Style = TFontStyles ( ) << fsItalic ;
    BitBtn1 -> Top = 258;
    BitBtn1 -> Left = 200;
    BitBtn1 -> Height = 24;
    BitBtn1 -> Width = 230;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormShow ( TObject *Sender ) {
    Label_Manual ( Sender );
    for ( i = 0; i < tam; i++ ) {
       if ( i % 10 == 0 )
        str_1 += "\n";
        str_1 += "  ";
      if ( i >= 0 && i < 9 ) {
           str_1 += "0";
       }
        str_1 += Vet [ i ];
    }
       Label1 -> Caption = str_1;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::BitBtn1Click ( TObject *Sender ){
    a++;
    str_1 = " ";
    //Casting
    Vetor = ( int ) atoi ( *Vet );
    for ( i = 0; i < tam; i++ ) {
       if ( i % 10 == 0 )
        str_1 += "\n";
        str_1 += "  ";
        Ve_tor [ i ] = ( Vetor + i );
      if ( Ve_tor [ i ] >= 0 && Ve_tor [ i ] < 10 ) {
           str_1 += "0";
       }
        str_1 += Ve_tor [ i ];
    }
        if ( a == 1 ) {
         Label2 -> Caption = str_1;
         }

       if ( a == 2 ) {
       srand ( time ( NULL ) );
       str_1 = " ";
       Label1 -> Caption = " ";
       for ( i = 0; i < tam; i++ ) {
       if ( i % 10 == 0 )
        str_2 += "\n";
        str_2 += "  ";
         j = i + rand ( ) % ( tam - i );
            char t = Ve_tor [ j ];
            Ve_tor [ j ] = Ve_tor [ i ];
            Ve_tor [ i ] = t;
       if ( Ve_tor [ i ] >= 0 && Ve_tor [ i ] < 10 ) {
           str_2 += "0";
       }
        str_2 += Ve_tor [ i ];
        }
       Label2 -> Caption = " ";
       Label3 -> Caption = str_2;
       }
       if ( a == 3 ) {
           Close ( );
       }
}
//---------------------------------------------------------------------------
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 -> Rectangle ( 05, 05, 595, 295 );
         SetTextColor ( Canvas -> Handle, RGB ( 255, 25, 2 ) );
         Canvas -> TextOut ( 80, 10, "CASTING DE TIPOS - DE CHAR PARA INTEIROS" );
         Canvas -> Font -> Size = 11;
         Canvas -> Font -> Color = clBlue;
         Canvas -> TextOut ( 210, 35, "Abaixo o vetor de caracteres" );
        if ( a == 0 ) {
        BitBtn1 -> Caption = "Converter para vetor de inteiros";
        }
        Canvas -> Font -> Size = 11;
        Canvas -> Font -> Color = clBlack;
        if ( a == 1 ) {
        Canvas -> TextOut ( 210, 35, "Abaixo o vetor de inteiros      " );
          BitBtn1 -> Font -> Color = clRed;
          BitBtn1 -> Caption = "Embaralhar o vetor de inteiros";
         }
         if ( a == 2 ) {
        Canvas -> TextOut ( 200, 35, "Vetor de inteiros embaralhados" );
            BitBtn1 -> Font -> Color = clBlack;
            BitBtn1 -> Caption = "Finalizar o programa agora";
         }
}
//---------------------------------------------------------------------------


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

#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
    TLabel *Label1;
    TBitBtn *BitBtn1;
    TLabel *Label2;
    TLabel *Label3;
    void __fastcall FormShow(TObject *Sender);
    void __fastcall BitBtn1Click(TObject *Sender);
    void __fastcall FormPaint(TObject *Sender);
private: // User declarations
String str_1;
String str_2;
int a;
void __fastcall Label_Manual ( TObject *Sender );
public:  // User declarations
 __fastcall TForm1 ( TComponent* Owner );
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif


object Form1: TForm1
  Left = 413
  Top = 118
  Caption = 'CASTING DE TIPOS - DE CHAR PARA INTEIROS'
  ClientHeight = 300
  ClientWidth = 608
  Color = clCream
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnPaint = FormPaint
  OnShow = FormShow
  PixelsPerInch = 96
  TextHeight = 13
  object Label1: TLabel
    Left = 40
    Top = 208
    Width = 3
    Height = 13
  end
  object Label2: TLabel
    Left = 536
    Top = 128
    Width = 3
    Height = 13
  end
  object Label3: TLabel
    Left = 536
    Top = 144
    Width = 3
    Height = 13
  end
  object BitBtn1: TBitBtn
    Left = 536
    Top = 80
    Width = 33
    Height = 25
    TabOrder = 0
    OnClick = BitBtn1Click
  end
end

Nenhum comentário:

Postar um comentário

Observação: somente um membro deste blog pode postar um comentário.