Description
This article describes how to translate an AnsiString variable
into an integer so that it can be used in a switch statement.
Two methods are introduced: the function method and the map method.
The project includes a form with two TButtons buttons: Button1 and
Button2.
Switch.cpp
Switch.h
Copyright © 1997-2002 Rodolfo A. Frino. All rights reserved.
#include <vcl.h>
#pragma hdrstop
#include "Switch.h"
#include <map>
//----------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//----------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//----------------------------------------------------------------------
int SwitchVariable( String S )
{
//Function method
String Values[] = {"value0", "value1", "value2", "value3", "value4",
"value5", "value6", "value7", "value8", "value9" };
for ( int i=0; i< ARRAYSIZE( Values ); i++ )
if ( S == Values[i] )
return i;
return -1; //Error: Illegal input
}
//---------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
//Function method
switch ( SwitchVariable( "value8" ) )
{
case 0:
ShowMessage( "0" );
break;
case 1:
ShowMessage( "1" );
break;
case 2:
ShowMessage( "2" );
break;
case 3:
ShowMessage( "3" );
break;
case 4:
ShowMessage( "4" );
break;
case 5:
ShowMessage( "5" );
break;
case 6:
ShowMessage( "6" );
break;
case 7:
ShowMessage( "7" );
break;
case 8:
ShowMessage( "8" );
break;
case 9:
ShowMessage( "9" );
break;
default: ShowMessage( "Illegal string value" );
}
}
//-----------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
//Map Method:
std::map
#ifndef SwitchH
#define SwitchH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TButton *Button1;
TButton *Button2;
void __fastcall Button2Click(TObject *Sender);
void __fastcall Button1Click(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif