Have started a paper on C++ and have, what most experienced C++ programmers would call, a small problem...
I am using Visual Studio 2008 and coding in Visual C++ with .NET. I am trying to code the tiniest of applications that will add a new line into a textbox everytime a button is clicked. Adding new lines is simple enough, but I am wanting to add an incrementing integer with each line, eg if I click on a button the first time, "This is line 1" gets added into the textbox, and on second click "This is line 2" gets added into the textbox. I am a little rusty on my programming and can't think of a looping structure that will enable this.
Here is the code (with some pseudocode) for the button's handler below:
private: System::Void addLine_Click(System::Object^ sender, System::EventArgs^ e) {
int i = 0;
if(button is clicked){
listBox->Items->Add("This is line " + i);
i++;
}
}
Should output something like:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
.
.
.
This is line i
The name of my button is "addLine" and the name of the list box I want these lines to appear in is called "listBox".
Thanks in advance for helping this C++ noob :).
i
is a local variable so it will loose its scope whenever the function exits. Either you need to declare i as static
or make it as a class variable.
private: System::Void addLine_Click(System::Object^ sender, System::EventArgs^ e) {
static int i = 0;
if(button is clicked){
listBox->Items->Add("This is line " + i);
i++;
}
}
我需要成为该类的成员-否则增量将无法在函数调用中幸免。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.