How to transfer CheckListBox values for an array? - c++builder

I need get values of an CheckListBox and transfering for an array. When i select the options from CheckListBox in order, for example(01, 02, 03) the results are correct, but if i selecting out of order, for example (04, 05, 06) the array don't get the values and the array values are 0.
My code:
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
CheckListBox1->Items->Add("01");
CheckListBox1->Items->Add("02");
CheckListBox1->Items->Add("03");
CheckListBox1->Items->Add("04");
CheckListBox1->Items->Add("05");
CheckListBox1->Items->Add("06");
CheckListBox1->Items->Add("07");
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
float array[3];
int optionChecked=0;
for(int i=0; i<CheckListBox1->Count;i++) {
if(CheckListBox1->Checked[i] == true) {
array[i]= StrToFloat(CheckListBox1->Items->Strings[i]);
optionChecked++;
}
}
for(int i=0;i<optionChecked;i++) {
ShowMessage(array[i]);
}
}

You are accessing array using the wrong index. You use i but mean to use optionChecked. You also run the risk of accessing out of bounds since your array is too short. I would change the code to be like so:
float array[7];
int optionChecked=0;
for(int i=0; i<CheckListBox1->Count;i++) {
if(CheckListBox1->Checked[i] == true) {
array[optionChecked]= StrToFloat(CheckListBox1->Items->Strings[i]);
optionChecked++;
}
}
It would be wise to add some defensive code to assert that the length of array is equal to CheckListBox1->Count.

Related

Confused with error -- E2193 Too few parameters in call to '_fastcall TComponent::GetComponent(int)

I am trying to programmatically remove a selected component from its parent container using the code below (I may be using found incorrectly, but that is not the problem, suggestions are welcome):
void __fastcall TScrollControlsListContainer::RemoveItem(TWinControl* ctrl)
{
// find control in vector containing TWinControl(s)
std::vector<FWinControl*>::iterator found = std::find_if(FWinControls.begin(), FWinControls.end(), IsCtrl(ctrl));
if(found != FWinControls.end())
{
Components->RemoveComponent(dynamic_cast<TComponent*>(found));
//[bcc32 Error] ScrollControlsListContainer.cpp(208): E2193 Too few parameters in call to '_fastcall TComponent::GetComponent(int)' Full parser context
FWinControls.erase(found);
}
}
I am confused about the error, as only one parameter is required according to the help file example below:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int I;
TComponent *Temp;
Memo1->Lines->Add("Components removed: ");
Form2->Memo1->Lines->Add("Components added: ");
for (I = ComponentCount - 1; I >= 0; I--)
{
Temp = Components[I];
// Move only the components that are not controls.
if (dynamic_cast<TControl *>(Temp) == NULL)
{
RemoveComponent(Temp);
Memo1->Lines->Add(Temp->Name);
Form2->InsertComponent(Temp);
Form2->Memo1->Lines->Add(Temp->Name);
}
}
}
What am I missing here?

dart: access function from list

Edit: i know, always call the first element on list, it isnt the point. i want to call numbers[0] func. and it regenerate new int.actually codes are not same which mine, i have a custom class which based on functions with random int and i need to use list of my custom class , so if i use func in list it will be awesome, how can i make new numbers list each time. when app start list regenerated, but i want when i call the list, it will regenerated
i want to print new int for each print but it prints same int , i tried so many thing and i cant figure out
void main{
int ramdomint(){
final _random = new Random();
int _num = _random.nextInt(100);
return _num;
}
List<int> numbers=[ramdomint(),ramdomint(),ramdomint()];
void printNums(){
for(var i=0;i<3;i++){
List<int> newNumbers =new List.from(numbers); //what can i use for this?
print(newNumbers[0]); //edit:i dont want [i], iwant to use ewNumbers[0] for new int for each time
}
}
printNums();
// expected new int for each but same one
}
solution from a friend:
import 'dart:math';
int get ramdomint => Random().nextInt(100);
List<int> get numbers => [ramdomint, ramdomint, ramdomint];
void main() {
for (var i = 0; i < 3; i++) {
print(numbers[0]);
}
}
Do not nest functions. Move ramdomint and printNums outside main function.
Add an empty list of arguments to the main function.
printNums: pass list of numbers as an argument.
printNums: you don't need to copy the list to the newNumbers if you want only to display the content of the list.
printNums: the problem is, you access only first element of the list (with 0 index).
import 'dart:math';
void main() {
List<int> numbers = [ramdomint(), ramdomint(), ramdomint()];
printNums(numbers);
}
int ramdomint() => Random().nextInt(100);
void printNums(List<int> numbers) {
// Easier way:
for (int item in numbers) {
print(item);
}
// Your way:
for (int i = 0; i < numbers.length; i++) {
print(numbers[i]);
}
}
EDIT:
According to #jamesdlin's comment, you can extend list class to randomize unique values in the list:
import 'dart:math';
void main() {
var numbers = <int>[]..randomize();
printNums(numbers);
}
void printNums(List<int> numbers) {
// Easier way:
for (int item in numbers) {
print(item);
}
// Your way:
for (int i = 0; i < numbers.length; i++) {
print(numbers[i]);
}
}
extension on List<int> {
void randomize({
int length = 3,
int maxValue = 100,
}) {
final generator = Random();
for (var i = 0; i < length; i++) {
add(generator.nextInt(maxValue));
}
}
}
The Problem here is that you are creating a list from the numbers list and accessing only the first element.
So it always prints the first element.
import 'dart:math';
void main() {
int ramdomint(){
final _random = new Random();
int _num = _random.nextInt(100);
return _num;
}
List<int> numbers=[ramdomint(),ramdomint(),ramdomint()];
void printNums(){
for(var i=0;i<3;i++){
print(numbers[i]);
}
}
printNums();
}
Don't want newNumbers, because it is already in List.
and the usage of List.from() - Documentation
Hope that works!

MQL4 Send objects array as function parameter

I had the function as a class member with an array of my custom object as a parameter:
class Stochastic { ... some class which sent into initializeStochastics method as param };
class StochasticInitializer {
public:
Properties *properties[8];
public:
StochasticInitializer(void) {
this.properties = ...
}
public:
void initializeStochastics(Stochastic& *stochastics[]) { // This param is my problem
for (int i = 0 ;i < ArraySize(properties); i++) {
if (properties[i].enabled) {
stochastics[i] = new Stochastic(properties[i]);
}
}
}
};
My errors:
'&' - comma expected
']' - declaration without type
']' - comma expected
'initializeStochastics' - wrong parameters count
'stochastics' - undeclared identifier
I take syntax from here, but perhaps it solution for MQL5.
Can I send an array of class instances as a method parameter in MQL4? If "yes" - how, if no - it answers too.
Everything works (almost works) just decide whether you are going to create an global array or with pointer access (need to delete it after you finish). Here is example of pointers. Also, please provide MCVE next time, because someone needs to write all that useless stuff like properties&stoch classes to make it testable.
class Properties
{
public:
bool enabled;
int periodK;
Properties(bool _enabled,int k):enabled(_enabled),periodK(k){}
~Properties(){}
};
class Stochastic
{
public:
int periodK;
Stochastic(){}
~Stochastic(){}
Stochastic(Properties *prop):periodK(prop.periodK){}
double get(const int shift,const int buffer=0)const{return iStochastic(_Symbol,0,periodK,3,3,MODE_SMA,STO_LOWHIGH,buffer,shift);}
};
class StochasticInitializer
{
public:
Properties *properties[8];
StochasticInitializer()
{
Deinit();
properties[0]=new Properties(true,5);
properties[1]=new Properties(true,13);
properties[2]=new Properties(true,14);
properties[3]=new Properties(true,15);
properties[4]=new Properties(true,16);
properties[5]=new Properties(true,17);
properties[6]=new Properties(true,18);
properties[7]=new Properties(false,19);
}
~StochasticInitializer(){Deinit();}
void Deinit(const int reason=0){ for(int i=0;i<ArraySize(properties);i++)delete(properties[i]); }
void initializeStochastics(Stochastic *&stochastics[])// THIS IS WHAT YOU NEED IN CASE OF POINTERS
{
for(int i=0;i<ArraySize(properties);i++)
{
if(properties[i].enabled)
{
stochastics[i]=new Stochastic(properties[i]);
}
}
}
};
StochasticInitializer initializer;
void OnTick()
{
Stochastic *array[8]; //THIS IS ARRAY OF POINTERS
initializer.initializeStochastics(array);
for(int i=0;i<ArraySize(array);i++)
{
printf("%i %s: %d %s",__LINE__,__FILE__,i,CheckPointer(array[i])==POINTER_INVALID ? "null" : (string)array[i].periodK);
}
for(int i=ArraySize(array)-1;i>=0;i--)delete(array[i]);//DELETING POINTERS
ExpertRemove();
}

Code to locate a specific item in a linked list and remove it

For my Computer Science course we are needing to create 2 functions. One function needs to locate the serial position of the item being searched for (an int in this case) and the index of the previous item. The locateNode function (the function described above) needs to be used within the Remove function as well as other functions already written by the professor in the class. Remove is simply supposed to take the item before the one being removed and make it point to the item that was being pointed to by the removed item. Finally it will take the removed node and push it into an avail list within the same array (essentially there are 2 linked lists in the one array.) My functions are giving me the wrong output and I currently do not know which is wrong or if both functions are wrong.
void SortedList::Remove(ItemType anItem, bool& success)
// IN OUT
{
int previous, position;
success=locateNode(anItem, previous, position);
cerr<<success<<endl;
if (success)
{
int current=list[0].next;
list[previous].next=list[list[previous].next].next;
for (int i=1; i<position; i++)
{
current=list[i].next;
}
PushAvail(current);
}
} // end Remove
bool SortedList::locateNode(
ItemType anItem, int& previous, int& position) const
{
position=1;
previous=0;
int current=list[0].next;
bool isPresent = false;
for (int count=1; count <= size; count++)
{
if (list[current].item >= anItem)
{
if ( list[current].item == anItem)
{
cerr<<"Position "<< position<< endl;
cerr<<"Previous "<< previous<< endl;
isPresent = true;
}
return isPresent;
}
position++;
previous=list[previous].next;
current=list[current].next;
}
return isPresent;
}

How to put TEdit data into String C++ Builder

I am new in programming. Actually I am in 2nd year of college and starting an internship. They want me to do a program in C++ builder but I only know C. What I studied. And I don't have any knowledge about OOP.
So my question is.
I have TEdit1 and I want to verify if the data introduced in that textbox is a number. I know to verify if it is a number but I don't know how to put data from TEdit into string.
I wrote some code but it doesn't work.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int Size = Edit1->GetTextLen(); //Get length of string in Edit1
Size++; //Add room for null character
Char *Buffer = new Char[Size]; //Creates Buffer dynamic variable
std::auto_ptr<Char> Buffer(new Char[Size]);
Edit1->GetTextBuf(Buffer.get(),Size); //Puts Edit1->Text into Buffer
ShowMessage(Buffer);
}
And I get these errors:
E2034 Cannot convert 'std::auto_ptr<wchar_t>' to 'UnicodeString'
E2342 Type mismatch in parameter 'Msg' (wanted 'const UnicodeString', got std::auto_ptr<wchar_t>')
Can you please explain what i did wrong, or where i can found Embarcadero C++ Builder tutorials? I searched all google and didn't find something to help me.
Your code has several mistakes in it:
you are declaring two Buffer variables in the same scope. That is not allowed. You need to remove one of them.
you are passing the std::auto_ptr itself to ShowMessage(), but it expects a System::UnicodeString instead, thus the compiler error message. You can use the std::auto_ptr::get() method to get the wchar_t* pointer and pass it to ShowMessage(), as UnicodeString has a constructor that accepts wchar_t* as input:
ShowMessage(Buffer.get());
despite the above, you actually cannot use a pointer from new[] with std::auto_ptr to begin with. std::auto_ptr uses delete instead of delete[] to free the memory being pointed at. You must always use delete with new, and delete[] with new[]. So, while the code will compile, it will not free the memory correctly at runtime. C++11 introduced a new std::unique_ptr class to replace std::auto_ptr, and std::unique_ptr supports new[] and delete[] (however, C++Builder's 32bit compiler does not support C++11 yet - that is in the works - but its 64bit compiler does):
#include <memory>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int Size = Edit1->GetTextLen(); //Get length of string in Edit1
Size++; //Add room for null character
std::unique_ptr<Char[]> Buffer(new Char[Size]); //Creates Buffer dynamic variable
Edit1->GetTextBuf(Buffer.get(), Size); //Puts Edit1->Text into Buffer
ShowMessage(Buffer.get());
}
Now, with that said, if you are going to continue using C++Builder, you should learn how to use its built-in functionalities, like UnicodeString, which the RTL/VCL relies heavily on (use the System::String alias for most code, use UnicodeString directly only when absolutely necessary).
Your example can be vastly simplified using the TEdit::Text property:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
String s = Edit1->Text; //Get string in Edit1
ShowMessage(s);
}
The simplest solution to your problem would be to use the TCSpinEdit component instead of TEdit, as TCSpinEdit only allows numeric input in the first place, and has a Value property that returns an int:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int number = CSpinEdit1->Value;
ShowMessage("It is a number");
// use number as needed...
}
But, if you have to stick with TEdit, there are many ways to check a UnicodeString for numeric content.
You can set the TEdit::NumbersOnly property to true so the user cannot enter a non-numeric value (unless they use copy/paste, but let's ignore that for the moment), and then use the RTL's StrToInt() function, or System::UnicodeString::ToInt() method, to convert it as-is:
#include <System.SysUtils.hpp>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int number;
try
{
number = StrToInt(Edit1->Text);
// or: number = Edit1->Text.ToInt();
}
catch (const EConvertError&)
{
// not a number, do something else...
ShowMessage("It is not a number");
return;
}
ShowMessage("It is a number");
// use number as needed...
}
Or you can use the RTL's System::Sysutils::TryStrToInt() function:
#include <System.SysUtils.hpp>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int number;
if (TryStrToInt(Edit1->Text, number))
{
// use number as needed...
ShowMessage("It is a number");
}
else
{
// not a number, do something else...
ShowMessage("It is not a number");
}
}
Or you can use the STL's std::wistringstream class:
#include <sstream>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int number;
std::wistringstream iss(Edit1->Text.c_str());
if (iss >> number)
{
// use number as needed...
ShowMessage("It is a number");
}
else
{
// not a number, do something else...
ShowMessage("It is not a number");
}
}
Or, since you have a C background, you can use the C _wtoi() function (which doesn't offer much in the way of error checking):
#include <cstdlib>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int number = std::_wtoi(Edit1->Text.c_str());
if (number != 0)
{
// use number as needed...
ShowMessage("It is a valid number");
}
else
{
// not a number, do something else...
ShowMessage("It is not a valid number");
}
}
Or you can use the C wcstol() function:
#include <cstdlib>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
String s = Edit1->Text;
Char *p = s.c_str(), *end;
int number = std::wcstol(p, &end, 10);
if (end != p)
{
// use number as needed...
ShowMessage("It is a number");
}
else
{
// not a number, do something else...
ShowMessage("It is not a number");
}
}
Or you can use the C swscanf() function:
#include <cstdio>
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int number;
if (std::swscanf(Edit1->Text.c_str(), L"%d", &number) == 1)
{
// use number as needed...
ShowMessage("It is a number");
}
else
{
// not a number, do something else...
ShowMessage("It is not a number");
}
}

Resources