C ++ language basics (1)

Source: Internet
Author: User

Getting started
Function main function in variable C ++ Data Type C ++ operator C ++ array String Array string operation function

C ++ is a powerful language that can be used for tasks that other languages cannot do. However, this powerful feature comes at a cost. When you start to use C ++, you may encounter problems such as memory overflow and access failure, causing the program to crash. Here we will give a brief introduction to the basics of the C ++ language. The C ++ language has its own monograph. This book is still very thick, so don't expect me to be clear in just a few words. After learning this book and using C ++ builder for a general period of time, the reader finally gives a more in-depth understanding of the C ++ language.

C ++ can take full advantage of Object-Oriented Programming (OOP. Oop is not just a new term, but has its practical significance. It can generate reusable objects. The new term object, like the component described above, is the software block used to complete a specific programming task (the component is an object, but the object is not a component, which will be explained later ). Objects only display the required parts to users (programmers who use objects) to simplify object usage. All internal mechanisms that users do not need to know are hidden behind the scenes. All of this is included in the concept of object-oriented programming. Oop can be programmed in a modular way to avoid starting from scratch each time. The C ++ builder program is oriented to OOP, because C ++ builder uses a large number of components. After the component is generated (the component you generate or the component built in C ++ builder), it can be reused in any c ++ builder program. The components can also be expanded to generate new components with new functions through inheritance. The best thing is that the component hides all content details, allowing programmers to focus on making full use of the component.

Getting started
C language is available before C ++. c ++ is built on C language and is called "C language with classes ". This C language is still very important in today's c ++ programs. C ++ does not replace C, but supplements and supports C. The remaining part of this chapter and the following chapters mainly introduce the C language. In fact, the C language is introduced here. Only C ++ is transferred to C ++ in Lesson 2nd "C ++ basics. Readers do not have to worry about which is from C and which is from C ++, because all these are in C ++. C ++ is difficult to introduce in sequence, because all the features we will introduce are cross-cutting. I prepared an introduction and pieced it together. By the end of Lesson 3rd "Advanced C ++", you will have a complete understanding of the C ++ language. It doesn't matter if you don't have a certain concept. Some concepts must be fully understood after practice.

Variable
Let's start with the variable. Variable is actually the name assigned to the memory address. After declaring a variable, you can use it to operate data in the memory. The following are examples. Two variables are used in the following code segments. The statements at the end of each statement describe what happens when the statement is executed:
Int X; // variable declared as an integer variable
X = 100; // 'X' now contains the value 100
X + = 50; // 'X' now contains the value 150
Int y = 150; // 'y' declared and initialized to 150
X + = y; // 'X' now contains the value 300
X ++; // 'X' now contains the value 301
The new term variable is used as the computer memory address to store a value. Note that the value of X Changes During Variable operations. The C ++ operator of the Operation variable will be introduced later. Variables declared with warnings but not initialized contain random values. Because the memory to which the variable points has not been initialized, you do not know the value of the memory address.
For example, the following code
Int K;
Int y;
X = Y + 10; // oops!
In this example, the variable Y is not initialized in advance, so X may obtain any value. The exception is that the global variable and the variable declared with static modification are always initialized to 0. All other variables include random values before initialization or assignment. Variable names can contain uppercase letters, lowercase letters, numbers, and underscores (_), but cannot contain spaces or other special characters. The variable name must start with a letter or underscore. Generally, it is not good to start with an underscore or double underscore below the variable name. The maximum length allowed by the variable name varies with the compiler. It is absolutely safe if the variable name is kept below 32 characters. In reality, any variable name that exceeds 20 characters is not practical.
The following is an example of a valid variable name:
Int averylongvariablename; // a long variable name
Int my_variable; // a variable with an underscore
Int _ x; // OK, but not advisedint X; // uppercase variable name
Int labe12; // a variable name containing a number
Int getitemsincontainer (); // thanks Pete!
The variable names in C ++ are case-sensitive. The following variables are different: int xpos; if your original language is case-insensitive (such as Pascal ), then, the language considering case sensitivity may be unsuitable.

C ++ Data Type
The new term C ++ defines how the compiler stores information in memory. In some programming languages, you can assign any numeric type to a variable. For example, the following is an example of the basic code: x = 1; X = 1000; X = 3.14; X = 457000; in basic, the translator can consider allocating space based on the number length and type. In C ++, you must declare the variable type before using the variable: int X1 = 1; int x = 1000; float y = 3.14; long z = 457000, the compiler can perform a type check to ensure that the program runs smoothly. Improper use of data types may cause compilation errors or warnings for Analysis and Correction before running. Some data types are signed and unsigned. The signed data type can contain positive and negative numbers, while the unsigned data type can only contain positive numbers. Table 1.1 lists the data types, memory size, and possible value ranges in C ++.
Table 1.1c ++ data type (32-bit program)
Data Type byte value range
Char 1-128 to 126
Unsigned char 1 0 to 255
Short 2-32,768 to 32,767
Unsigned short 2 0 to 65,535
Long 4-2,147,483,648 to 2,147,483,648
Unsigned long 4 0 to 4,294,967,295
Int 4 is the same as long
Unsigned int 4 and unsigned long
Float 4 1.2e-38 to 3.4e381
Double 8 2.2e-308 to 1.8e3082
Bool 1 true or false
From the table above, we can see that int and long are the same. So why do C ++ need to differentiate these two data types? This is actually a legacy issue. In a 16-bit programming environment, int requires 2 bytes, and long requires 4 bytes. In a 32-bit programming environment, both types of data are stored in four bytes. C ++ builder only generates 32-bit programs, so int and long are the same. In C ++ builder and Borland C ++ 5.0, bool is a real data type. Some C ++ compilers have the bool keyword, so bool is not a real data type. Sometimes bool is only a typedef, so that bool is equivalent to int. Typedef actually creates an alias to enable the compiler to draw an equal sign between one symbol and another. The syntax of typedef is as follows: typedef int bool; this tells the compiler that bool is the alias of Int. It indicates that only the double and float data types use floating point numbers (with the number of decimal points ). Other data types only involve integer values. Although the integer data type can also specify a number with a decimal point, the fractional part is discarded and only the integer part is assigned to the integer variable. For example: int x = 3.75; the value of X is 3. Note that this integer is not rounded to the nearest decimal point. By the way, floating point numbers are rarely used in most Windows programs. C ++ converts data types when necessary. Example: Short result; long num1 = 200; long num2 = 200; Result = num1 * num2; here I want to assign the product of two long integers to a short integer. Although this formula is mixed with two data types, C ++ can be used for conversion. What will happen to the calculation result? The result will surprise you. It is 25536, which is the result of the bypass (wrop. As shown in Table 1.1, the maximum value of a short integer is 32767. What if I add 1 to the maximum value? The result is 32768. This is actually the same as the car's mileage from 99999 to 00000. To illustrate this, enter and run the program contained in listing 1.3.
List 1.3wrapme.cpp
1: # include <iostream. h>
2: # include <conio. h>
3: # pragma hdrstop
4:
5: int main (INT argc, char ** argv)
6 :{
7: Short x = 32767;
8: cout <"x =" <x <Endl;
9: X ++;
10: cout <"x =" <x <Endl;
11: getch ();
12: Return 0;
13 :}
Some of the following lists do not have the following statements:
# Include <condefs. h>
This statement is automatically added when C ++ builder generates a new console application. This is not necessary in the program you are using, so it is omitted in the code list. The program running results are consistent regardless of whether this statement exists. Analysis output result: x = 32767 x = 32768 if int data type is used, this problem does not occur because the value range of int data type is between positive 2 billion, generally, there is no detour. However, the program may be slightly larger, because int requires 4-byte storage, while short only needs 2-byte storage. For most applications, this difference is not significant. The preceding section describes automatic type conversion. Sometimes C ++ cannot be converted. In this case, a compilation error may occur in the compiler, that is, cannot convert from X to Y (cannot be converted from X to Y ). The compiler may also warn that conversion might lose significant digits (conversion may lose a significant bit ). Prompt the compiler warning should be a compiler error because it indicates an error. We should try to generate a compilation without warning. Sometimes warnings cannot be avoided, but be sure to carefully check all warnings. The cause of the warning should be fully understood and corrected as much as possible.

C ++ Operator
Operator is used to operate data. Operator for computation, equality check, assignment, operation variables, and other strange work. C ++ has many operators. I don't want to list them all here. I only want to list the most common operators, as shown in the following table. Table 1.2 examples of commonly used C ++ Operators
Arithmetic Operators
+ Add x = Y + z;
-Minus X = Y-Z;
* Multiply x = y * z;
/Except x = y/z;
Value assignment operator
= Value x = 10;
+ = Value assignment and x + = 10; (equal to X = x + 10 ;)
-= Value assignment and subtraction X-= 10;
* = Value assignment and multiplication x * = 10;
/= Assign values and divide x/= 10;
& = Value assignment and X & = 0x02;
| = Assign a value or X | = 0x02;
Logical operators
& Logic and if (X & 0xff ){...}
| Logic or if (X | 0xff ){...}
Equality Operators
= Equal to If (x = 10 ){...}
! = Not equal to If (X! = 10 ){...}
<Less than if (x <10 ){...}
> Greater than if (x> 10 ){...}
<= Less than or equal to If (x <= 10 ){...}
>=Greater than or equal to If (x> = 10 ){...}
Unary operator
* Indirect operator int x = * Y;
& Amp; address operator int * x = & Y;
~ Non-x ~ 0x02;
! The logic is not if (! Valid ){...}
++ Incrementing operator x ++ (equal to X = x + 1 ;)
-- Decrease operator X --;
Class and structure Operators
: Scope resolution myclass: somefunction ();
-> Indirect member myclass-> somefunction ();
· Directly member myclass. somefunction ();
It can be seen that this list is longer and cannot be remembered at once. When using C ++, you will gradually become familiar with these operators. It must be noted that the incrementing operator can be either a forward incrementing (++ X) or a post-incrementing (x ++ ). The increment operator tells the compiler to increment first and then use the variable. Then, the increment operator allows the compiler to increment first with the variable value. For example, the following code:
Int x = 10;
Cout <"x =" <X ++ <end1;
Cout <"x =" <x <end1;
Cout <"x =" x <end1;
Cout <"x =" <++ x <end1;
The output result is as follows:
X = 10
X = 11
X = 12
X = 12
This is also the case with the drop-down operator. I don't want to talk too much about this content here, but the reader can read it patiently, as Peng Zi told Augusta, "OGU, be patient, rome was not built in one day ". It indicates that operators in C ++ can be overloaded ). Programmers can use standard overload operators to perform specific operations in specific classes. For example, you can use the overload increment operator in a class to increase the variable by 10 instead of by 1. Operator overload is an advanced C ++ technology, which is not described in detail in this book. You may find that some operators use the same symbol. The meaning of a symbol varies with the situation. For example, an asterisk (*) can be used as a multiplication number, a pointer is declared, or a pointer reference is canceled. It seems a little messy at the beginning. In fact, C ++ Programmers sometimes feel a little messy. More practices, you will gradually adapt. There are many examples in this book to introduce these operators. Readers do not have to memorize the role of each operator, but can understand its role through programs and code segments in learning.

Functions in C ++
A function is a code segment separated from the main program. These code segments are called (executed) when a specific action is required in the program ). For example, a function may take two values and perform complex mathematical operations on them. Then return the result. The function may take a string for analysis and return part of the analysis string. The new term function is a pre-defined service that is separated from the main program. Functions are an important part of various programming languages, and C ++ is no exception. The simplest function returns void without parameters (indicating that nothing is returned). Other functions may include one or more parameters and may return a value. The function name rule is the same as the variable name. Figure 1.5 shows the components of a function. The new term parameter is the value passed to the function, used to change the operation or indicate the operation degree.
Return type function name parameter table

Int somefunction (int x, int y ){
Function body → int z = (x * Y); Return Z; explain Return Statement
}
Figure 1.5 declare the components of a function before using the function. The function declaration or prototype tells the compiler function the number of parameters, the Data Type of each parameter, and the Data Type of the function return value. Listing 1.4 lists this concept. Prototype is a declaration or definition of the function appearance.
List 1.4muttiply.cpp
1: # include <iostream. h>
2: # include <conio. h>
3: # pragma hdrstop
4:
5: int multiply (INT, INT)
6: void showresult (INT );
7:
8: int main (INT argc, char ** argv );
9 :{
10: int X, Y, result;
11: cout <end1 <"Enter the first value :";
12: CIN> X;
13: cout <"enter the second value :";
14: CIN> Y;
15: Result = multiply (x, y );
16: showresult (result );
17: cout <end1 <end1 <"press any key to continue ...";
18: getch ();
19: Return 0
20 :}
21:
22: int multiply (int x, int y)
23 :{
24: Return x * Y;
25 :}
26:
27: void showresult (INT res)
28 :{
29: cout <"the result is:" <res <end1;
30 :}
Line 11 to 14 of this program uses the standard input stream CIN to take two numbers to the user, line 3 calls the multiply () function to multiply the two numbers, and line 3 calls showresult () the function returns the result of multiplication. Note the prototype declaration of the multiply () and showresult () functions in front of the main program. Only the Data Types of the return type, function name, and function parameters are listed in the prototype. This is the most basic requirement of function declaration. The function prototype can also contain the variable name used to document the function. For example, the function declaration of the multiply () function can be written as follows: int multiply (INT firstnumber, int secondnumber); here, the function of multiply () is very effective, but the code can be both explained and documented by the Code itself. Note that the definition of the function multiply () in listing 1.4 (22 to 25 rows) is out of the main function definition code segment (8 to 20 rows. The function definition contains the actual function body. The function body here is the most basic, because the function only multiply two parameters of the function and returns the result. In listing 1.4, the function multiply () can be called in multiple ways, and the results of variables, direct numbers, or other function calls can be passed:
Result = multiply (2, 5); // passing literal values
Result = multiply (x, y); // passing Variables
Showresult (multiply (x, y ));
// Return value used as
// Parameter for another function
Multiply (x, y); // return value ignored
Note that the return value is not used in the last example. In this example, it makes no sense to call the function multiply () without returning the value, but the return value is often ignored in C ++ programming. Many functions return a value after performing a specific action to indicate the function call status. Sometimes the return value is irrelevant to the program and can be ignored. If the returned value is ignored, this value is abandoned without any harm. For example, the previous sample program ignores the return value of the getch () function (returns the ASCII value of the key ). A function can call other functions or even itself. This call is called recursion ). This is a complicated issue in C ++ programming. The new term "recursion" is the process in which the function calls itself. The functions described in this section refer to independent functions in C or C ++ programs (independent functions are not members of classes ). The independent functions in C ++ can be used in the same way as those in C. However, C ++ further deepens the functions and will introduce them later in C ++.
// This article from C ++ builder research-http://www.ccrun.com/article.asp? I = 363 & D = 766y3r
BR> function rules
· The function can take any number of parameters or does not take any parameters.
· A function can return a value without forcing the function to return a value.
· If the function returns the void type, the value cannot be returned.
If you want a void-type function to return a value, a compilation error occurs. A void-type function does not need to contain a return statement, but can also contain this statement. If no return statement exists, the function is automatically returned when it reaches the end of braces.
· If the function prototype indicates that the function returns a value, the function body should contain a return statement for the returned value. If the function does not return a value, a compilation error occurs.
· A function can take any number of parameters, but only one value can be returned.
· Variables can be passed to functions by value, pointer, or reference (will be introduced later ).
Syntax: The Declaration (prototype) Format of the function statement is as follows: ret_type function_name (argtype_1 arg_1, argtype_2 arg_2,..., argtype_n arg_n );
The function declaration indicates the function to be included in the Code. The returned data type (ret_type) and function name (function_name) of the function should be displayed, indicating the order of the data elements required by the function (arg_1, arg_2 ,..., arg_n) and type (argtype_1, argtype_2 ,... argtype_n ).
The format of the function statement is as follows:
Ret_type function_name (argtype_1 arg_1, argtype_2 arg_2,..., argtype_narg_n );
{Statements;
Return ret_type ;}
The function definition indicates the code block (statements) that constitutes the function. The returned data type (Ret type) and function name (function_name) of the function should be displayed, including the variable (arg_1, arg_2 ,..., arg_n) and type (argtype_1, argtype_2 ,... argtype_n ).

Main () function
The C ++ program must have the main () function. The main () function is the entry point of the program. Each sample program described above has the main () function. However, not all c ++ programs have traditional main () functions. Windows program entry point functions written in C or C ++ are called winmain () instead of traditional main () functions. It indicates that the C ++ builder GUI application has winmain (), but is hidden. C ++ builder allows you to focus on the creation of user interfaces and other parts without considering the low-level details of Windows programs. The main () function is similar to other functions and has the same components. In a 32-bit console application, C ++ builder generates the default main () function with the following prototype: int main (INT argc, char ** argv); this main () take two parameters in the function form and return an integer value. As mentioned above, numeric values are passed to the function when a function is called. However, the main () function is not directly called, but is automatically executed when the program is running. So how does the main () function obtain parameters? The method is obtained from the command line. It is described as follows: Assume that a Win32 console application needs to run the following command line at the DOS prompt: grep wm_killfocus handle-I
Here we need to use the command line variable wm_killfocus, D, and I to start the grep program. We want to demonstrate how to change it into argc and argv in the main () function. first, the argc variable contains at least 1 Number of parameters passed in the command line, because the program name is also counted as a parameter. The variable argv is an array containing the pointer of a string. This array contains each string passed in the command line. In this example:
Argc contains 4
Argv [0] contains C: | cbuilder | bin | grep.exe
Argv [1] contains wm_killfocus
Argv [2] contains d
Argv [3] contains I
Next we will use a small program to verify this fact. Generate a new console application in C ++ builder and enter the program shown in listing 1.5. List 1.5argstest.cpp
1: # include <iostream. h>
2: # include <conio. h>
3: # pragma hdrstop
4:
5: int main (INT argc, char ** argv)
6 :{
7: cout <"argv =" argc <end1;
8. For (INT I = 0; I <argc; I ++)
9. cout <"parameter" <I <":" <argv [I] <end1;
10. cout <end1 <"press any key to continue ...";
11: getch ();
12: Return 0;
13 :}
Save the project as arstest. Instead of clicking the run button, select project | build all in the main menu. In this way, only the project is created and no program is executed. After the project is completed, select Run | parameters from the main menu and enter the following content in the runparameters field of the runparameters dialog box: One Two Three "Four Five" six and then click the run button, the program runs with the specified command line parameters. Another method is to run the program at the DOS prompt using the following command line: When arstest One Two Three "Four Five" Six is running, it displays the number of incoming changes, then list each variable. Run the command several times and provide variable elements for different command lines each time. Pay attention to the result.
In most programs, the return value of the main () function is not important because the return value is usually not used. In fact, the main () function is not required to return a value. The main () function has multiple forms. The following statements are valid: Main (); int main (); // same as abve
Int main (void); // same as abve
Int main (INT argc, char ** argv );
Void main ();
Void main (INT argc, char ** argv );
There are more forms. If you do not want to use the command line variable, you can use the first main () function form, which does not take the parameter (empty in parentheses) returns an int (if not specified, the default return value is returned ). In other words, the most basic form of the main () function does not take the parameter and returns an int.

Array
Any inherent data type of C ++ can be put into an array. An array is a set of values. For example, assume that you want to save an integer array and put five integer values. You can declare an array as follows: int myarray [5]; here the compiler matches the memory space shown in Figure 1.7 for the number of components. Since each int needs to be stored in 4 bytes, the entire array occupies 20 bytes of memory.
Marray [0] marray [1] marray [2] marray [3]
Marray [4]
Baseaddrbasseaddr + 4 baseaddr + 8
Baseaddr + 12 baseaddr + 16
After declaring the array, you can use the following script operator ([]) to fill in the value:
Myarray [0] =-200;
Myarray [1] =-100;
Myarray [2] = 0;
Myarray [3] = 100;
Myarray [4] = 200;
As shown in the preceding figure, the array in C ++ is based on 0. In the subsequent program, you can use the script operator to access each element of the array:
Int result = myarray [3] + myarray [4]; // result will be 300
Another simple method is as follows:
Int myarray [5] = {-200,-100,200, 0 };
Further, if you know the number of elements in the array and fill the array when declaring the array, You can omit the array length when declaring the array. For example: int myarray [] = {-200,-100,200, 0,}; this is feasible, the compiler can determine the number of elements in the array and the memory space allocated to the array from the given value table.
Arrays can be multidimensional. To generate a two-dimensional integer array, you can use the following code:
Int mdarray [3] [5];
In this way, 15 int spaces are allocated (60 bytes in total ). The elements of an array can be accessed like a one-dimensional array. Only two script operators must be provided: int x = mdarray [1] [1] + mdarray [2] [1];
Figure 1.8 How a two-dimensional array looks like in the memory warning do not reload the end of the array.
A powerful feature of C ++ is its direct access to memory. Due to this feature, C ++ cannot prevent you from writing to a specific memory address, even if the address is not accessible by the program. The following code is valid, but may cause program or windows to crash: int array [5]; array [5] = 10; this is a common error because the array is based on 0, the biggest goal should be 4 rather than 5. If the end of the array is reloaded, you cannot know which memory is rewritten, making the results unpredictable, and even causing program or Windows crash. This type of problem is hard to diagnose, because the affected memory usually takes a long time to access and then crashes (which makes you confused ). Therefore, be careful when writing arrays.
Array rules
· The array is based on 0. The first element in the array is 0, the second element is 1, and the third element is 2.
· The array length should be a compilation constant. During compilation, the compiler must know how much memory space is allocated to the array. You cannot use variables to specify the length of an array. Therefore, the following code is invalid and may cause compilation errors:
Int x = 10; int myarray [X]; // compiler error here ·
Be careful not to reload the end of the array.
· Allocate large arrays from stacks rather than stacks (see later ). · You can use variables to specify the array length for arrays allocated from stacks. For example: int x = 10; int * myarray = new int [X]; // This is OK

Character array
It is strange that C ++ does not support string variables (variables for text placement). Strings in C ++ are represented by arrays of char data types. For example, you can assign a variable to a char array as follows:
Char text [] = "this is a string .";
This allocates 18 bytes of memory space in the memory to store strings. Based on your comprehension, you may find that the string contains only 17 characters. The reason for 18 bytes allocation is that the string must end with a null termination, and C ++ counts the null termination as one character when allocating memory space.
The new term terminate null is a special character, expressed as | 0, which is equal to the value 0. When the program encounters 0 in the character array, it indicates that it has reached the end of the string. To illustrate this, enter and run the following console applications.
List 1.6nulltest.cpp
1: # include <iostream. h>
2: # include <conio. h>
3: # pragma hdrstop
4:
5: int main (INT argc, char ** argv)
6 :{
7: Char STR [] = "this is a string .";
8. cout <STR <end1;
9. Str [7] = '/0 ';
10. cout <STR <end1
11. cout <end1 <"press any key to continue ...";
12: getch ();
13: Return 0;
14 :}
At the beginning of the analysis, the character array contains the string this is a string and a termination null, which is sent to the screen through cout. In the next row, the first element of the array is assigned a value of | 0, that is, null is terminated. The string is sent to the screen again, but only this is displayed. The reason is that the computer determines that the strings in the array are terminated on 7th elements, and the remaining strings are still in the memory space, but are not displayed because null is terminated. Figure 1.10 demonstrates the character array before and after a statement that assigns 7th elements of an array to | 0.
Before
Thi
Sisastri
Ng./0
After
This
Is/0 ASTRI
Ng./0
Figure 1.10 content of the character array
You can also assign a value of 0 instead of '| 0' in listing 1.6, and the result is the same, because the number 0 is equivalent to the char data type' | 0. For example, the following statements are equivalent:
STR [7] = '| 0 ';
STR [7] = 0;
It indicates that the single quotation marks and double quotation marks in the C ++ program are different. When assigning null or other character values to an array element, you must use single quotes. The single quotation mark is used to convert the character in the quotation mark into an integer value (the ASCII value of the character), and then store the value in the memory address. Double quotation marks must be used to assign a string to a character array. If the quotation marks are used incorrectly, the compiler may encounter a compilation error.

String operation functions
If you have used a programming language with the string data type, you may not get used to it. Others share the same feeling. Therefore, the standard C Language Library provides several string operation functions. Table 1.3 lists the most common string operation functions and their usage instructions. For detailed descriptions and examples of each function, see the online help of C ++ builder.
Table 1.3 string operation functions
Function Description
Strcat () Concatenates the string to the end of the target string
Strcmp () compares two strings for Equality
Strcmpi () compares two strings to determine whether they are equal, case insensitive
Strcpy () copies the string content to the target string
Strstr () scan the first string in the string
Strlen () returns the string length.
Strupr () converts all characters in the string to uppercase
Sprintf () creates a string based on several parameters
This section describes how to handle strings in C. Most C ++ compilers provide the cstring class to simplify string processing (the C ++ builder visual component library contains an ansistring class that can process string operations. The ansistring class is described in detail in the online help of C ++ builder ). Although the string processing method in C language is troublesome, It is not out of date. c ++ programmers often use the string processing method in C language when using strings such as cstring and ansistring. Here, we do not want to illustrate every function in the table, but just want to give two of the most commonly used functions. The strcpy () function copies a string to another string. The source string can be a variable or a direct string. For example, the following code:
// Set up a string to hold 29 characters
Char buff [30];
// Copy a string literal to the buffer
Strcpy (buff, "this is a test."); // display it
Cout <buff <end;
// Initialize a second string buffer
Char buff2 [] = "a second string .";
// Copy the contents of this string to the first Buffer
Strcpy (buff, buff2 );
Cout <buff <end1;
The character array is easier to overload the end of a number than the number array. For example, the following code:
Char buff [10] = "a string"; // later ....
Strcpy (buff, "this is a test."); // oops!
Here we create an array of 10 characters, which initially specifies a string of 9 bytes (remember to terminate null ). Later, I may forget the length of the array. I copied the 16-byte string to the buffer and overloaded the array with six bytes. This small error erased six bytes from a memory location. Therefore, be careful when copying data to character arrays. Another common string function is sprintf (). This function can combine text and numbers to create a formatted string. The following example adds two numbers and uses sprintf () to create a string to report the results:
Char buff [20];
Int x = 10*20;
Sprintf (buff, "the result is: % d", X );
Cout <Buff;
When this code segment is executed, the program displays the following results: the result is: 200
In this example, % d tells the sprintf () function that there is an integer value, inserts the variable X at the end of the format string, and tells sprintf () to put the value of variable X at this position of the string. Sprintf () is a special function that can take multiple variable elements. You must provide the target buffer and format string, but the number of variables after the format string is a variable. The sprintf () Example below uses another three yuan:
Int x = 20;
Int y = 5;
Sprintf (buff, "% d + % d", X, Y, x + y );
Cout <Buff;
The result displayed on the screen is as follows: 20 + 5 = 25
The single slash in the C ++ string represents a special character. For example, '/N' indicates a new line character, and'/t' indicates a table break. To put the actual slash in the string, use the double slash as follows:
Strcpy (filename, "C: // windows // system // win. ini ");
Many programmers have forgotten this simple fact and are hard at night. This is a common mistake, not to mention I didn't tell you. Sprintf () has a brother named wsprintf (), which is a sprintf () for Windows. These two functions may be used at the same time in a Windows program. Wsprintf () is similar to sprintf (). The only difference is that the floating point number cannot be placed in the format string. Both functions can be used in the C ++ builder program, but sprintf () is better, because it fully supports floating point numbers (one character can be entered less ). For more information about sprintf (), see the online help of C ++ builder.
 
A string array can contain both character arrays and character arrays ). This may sound a bit complicated. In fact, it has been used in the previous arstest program. Such Arrays can be allocated as follows:
Char strings [] [20] = {
"This is string 1 ",
"This is string 2 ",
"This is string 3 ",
"This is string 4 "};
This code generates an array of four strings, each containing a maximum of 19 characters. Although this string array can be used, the C ++ Builder provides a simpler string array processing method (which will be introduced later in C ++ builder ). If the string array is frequently used, you should check the standard template library (STL ). STL provides a more convenient way to store and operate string arrays than to use C-language character arrays. STL also has a string class.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.