首页 General C Programming Examples

General C Programming Examples

举报
开通vip

General C Programming ExamplesGeneral C Programming Examples GENERAL C PROGRAMMING EXAMPLES TABLE OF CONTENTS INTRODUCTION 1. PROGRAM FORMAT C PROGRAM FORMAT USER-DEFINED FUNCTIONS IN C LOADRUNNER SCRIPTS AND C 2. DATA TYPES INTEGER TYPE FLOAT TYPE CHAR TYPE FORMAT CONTROL EXERCISE ...

General C Programming Examples
General C Programming Examples GENERAL C PROGRAMMING EXAMPLES TABLE OF CONTENTS INTRODUCTION 1. PROGRAM FORMAT C PROGRAM FORMAT USER-DEFINED FUNCTIONS IN C LOADRUNNER SCRIPTS AND C 2. DATA TYPES INTEGER TYPE FLOAT TYPE CHAR TYPE FORMAT CONTROL EXERCISE 2.1 3. CONTROL FLOW BOOLEAN OPERATORS IF STATEMENTS SWITCH STATEMENT EXERCISE 3.1 FOR LOOPS WHILE DO WHILE BREAK AND CONTINUE EXERCISE 3.2 THE ? OPERATOR 4. ARRAYS AND STRINGS ARRAYS STRINGS EXERCISE 4.1 STRING MANIPULATION MULTI-DIMENSIONAL ARRAYS 1 5. FILE PROCESSING FILE DECLARATION FILE OPENING FILE READING EXERCISE 5.1 FILE WRITING EXERCISE 5.2 6. FUNCTIONS USER-DEFINED FUNCTIONS EXERCISE 6.1 INCLUDE FILES EXERCISE 6.2 7. MISCELLANEOUS FUNCTIONS SYSTEM RANDOM NUMBERS SOLUTIONS EXERCISE 2.1 EXERCISE 3.1 EXERCISE 3.2 EXERCISE 4.1 EXERCISE 5.1 EXERCISE 5.2 EXERCISE 6.1 2 Introduction My initial plan was to create a C reference manual for the Mercury Test Team. This is because LoadRunner scripts consist of calls to LoadRunner functions, which are essentially C function libraries. Since C forms the basis for LoadRunner scripts, most of the functions in C are supported in LoadRunner. Expertise in C will help you customize and improve the scripts greatly. So we thought that a C reference manual would be very useful. Though LoadRunner is based on C, there are a few variations and exceptions to the C functions that are supported in LoadRunner. Moreover, I did not want to add the overhead of owning a C compiler to go through the exercises in this manual. So I thought I?d create a manual that would work with Virtual User Generator (Vugen). I am hoping that by the time you get to this manual, you are already familiar with the components of LoadRunner. All exercises in this manual can be compiled and run in Vugen. As I discuss each topic in C, I?ll also discuss how it differs in LoadRunner and the context in which this function might be useful. This will both familiarize you with C from a LoadRunner perspective, and make you comfortable with using custom coding in LoadRunner. If you are already comfortable with C, you might be able to skim through this manual in no time. Please note that the purpose of this manual is not to make a C expert out of you; most of the concepts and exercises in here are very elementary. This will just be a quick C/LoadRunner reference. Hope you find this work useful. 3 1. Program Format In this section, we will discuss the C program format and how it relates to LoadRunner. C Program Format Every programming language has a set of rules, called syntax of the language, that govern how legal programs are constructed. A program in C can be made up of many components, sometimes spread over several files. We will take a look at a very simple but popular C program: #include main() { /* This program prints “Hello World!” */ printf(“Hello World!”); } The first line, #include, is a signal that some information should be added to the program from an external file, either a system file as in this case ( is a standard input and output library), or a user defined file. The body of the program is contained in main(), encapsulated by { }. Comments in C are surrounded by /* and */. The C compiler ignores all text within the comments. The only statement in the program, printf (“Hello World!”) instructs the program to print the “Hello World!” to the standard output. Now, the function printf is defined in stdio.h, and that is the reason we included stdio.h above the main. User-Defined Functions in C We are violating every rule in the art of C-instruction by introducing user-defined functions so early in the game. But it is very important to understand user-defined functions to introduce how LoadRunner scripts tie into C programming. At this point, we will introduce user-defined functions at a conceptual level, and get into the details in a later section. In the Hello World program, we used the function printf, which prints the given message to the standard output. The printf function is a standard built-in function in C. So the compiler understands the action requested by the use of that function. But it is often 4 necessary in programming to create your own functions to accomplish certain tasks. These functions are called user-defined functions. For example, lets say you have to print the following text a number of times in your program: $$$$$$$$$$$ Hello World! $$$$$$$$$$$ This can be accomplished by creating a function that will print the above text and calling the function a number of times as required. This is what your program will look like: #include my_function() { /* Text generating code */ printf(“$$$$$$$$$$$\n”); printf(“Hello World!\n”); printf(“$$$$$$$$$$$\n\n”); } main() { my_function(); /* call 1 */ printf(“This program demonstrates user-defined functions.\n\n”); my_function(); /* call 2 */ } In the above program, we defined a function named my_function, which was called twice in the main (call 1 and call 2). The following will be the output of the above program. You can see that every time the function my_function was called, the 3-line text output was generated. $$$$$$$$$$$ Hello World! $$$$$$$$$$$ This program demonstrates user-defined functions $$$$$$$$$$$ Hello World! $$$$$$$$$$$ 5 By creating a function to generate the text output, we avoided the need to write the text-generating code over and over in the main program. We can simply call the function as many times as we need. The above is a trivial example of a user-defined function with a single purpose. Multi-purpose and reusable functions can be created by use of parameters. This will be discussed in a later section. Now that we have an idea of what a C function is, let us look at how LoadRunner scripts relate to C. 6 LoadRunner Scripts and C In Vugen, you may have noticed that a LoadRunner script consists of init, actions and end sections. In LoadRunner 6.0 and above, you can have multiple actions sections as shown in figure 1.1. Figure 1.1: Vugen Lets look at the above script from a C programming point of view. When you record a script into different sections of Vugen, each section will be recorded like a regular C function. In the above figure, vuser_init, Action1, Action2 and vuser_end will be our 4 functions. If the above script is set to run 3 iterations, this is how an equivalent C program would look like: main() { /* calling init section */ vuser_init(); /* calling actions section iteration 1 */ Action1(); Action2(); /* calling actions section iteration 2 */ Action1(); Action2(); /* calling actions section iteration 3 */ Action1(); Action2(); 7 vuser_end(); } where each function is defined in the Vugen script. There is no main in LoadRunner. It is automatically taken care of behind the scenes. Different sections of the scripts are the only visible parts of the program. What goes on behind the scenes is a lot more ugly, but the above is a simplistic representation of the idea. The vuser will execute all actions corresponding to that section when a function is called. It is important to understand that each section in the script is treated like a user-defined function. Example: In the above script, lets say each section prints a message identifying itself. The following will be the output in the execution log of Vugen: Virtual User Script started vuser_init.c(3):You are in vuser_init Running Vuser... Starting iteration 1. Action1.c(3):You are in Actions1 Action2.c(3):You are in Actions2 Ending iteration 1. Starting iteration 2. Action1.c(3):You are in Actions1 Action2.c(3):You are in Actions2 Ending iteration 2. Starting iteration 3. Action1.c(3):You are in Actions1 Action2.c(3):You are in Actions2 Ending iteration 3. Ending Vuser... vuser_end.c(3):You are in vuser_end Vuser Terminated. In a real script, each of these functions might be exercising the application under test (AUT), rather than just printing pretty little messages. The idea behind this chapter was just to familiarize you with the LoadRunner program structure and compare it to C. We will focus on different elements of C in the upcoming sections. 8 2. Data Types I think “Hello World” is the only respected program in the world that does not contain variables. If you want your program to do anything remotely interesting, you will have to use variables. In this chapter, we will see the different data types in which a variable can be declared. For example, a variable called count can be declared as an integer type. int count = 0; Now the variable count can assume any integer value during the program execution. There are limitations on the size and precision of each data type, which we will discuss shortly. All variables in C must be declared before they can be used. Integer Type As the name suggests, this type is used to declare variables to contain integer values. Typically, short integers range in values between –32,768 to 32767 (The precision depends on the number of bits used). Long integer, or just declared as int in LoadRunner, ranges in values from –2147483648 to 2147483648 (No shortage of values there!). Unless you are using a whole lot of variables, which is not the case typically in LoadRunner, you don?t have to worry about memory considerations. But note that a short int takes lesser space in memory compared to a regular integer. Float Type Float type is used for non-integral values like the one below: float x = 2.564; -3838 Float ranges in values from 10 to 10. For greater range, you can use double, which -308308 ranges in values from 10 to 10. We will rarely need this data type in LoadRunner. Char Type The character (declared as char), is used to denote characters. char x = „A?; Though the variable x is a character, it actually stores the integer 65 internally. So integers and characters are interchangeable (Disclaimer: The word interchangeable has been used very loosely here, please use caution!). So the letter A has an integer value of 65, letter B is 66.. and so on. 9 We will see an example soon that will clarify the data types further. Before we get there, we need to understand format control for output in C. Format Control When you print in C, you also need to specify the format for output. Consider the following example. main() { int a = 5; float x = 3.14; printf(“Value of a = %d and b = %f”,a,b); } The above program will produce the following output: Value of a = 5 and b = 3.140000 Here, %d is used to denote an integer value and %f a floating point value. Similarly, %c corresponds to character values. Now, consider the example below: main() { int a = 5; float x = 3.14; printf(“Value of a = %03d and x = %05.2f”,a,x); } The above program will produce the following output: Value of a = 005 and b = 03.14 %03d forces a to be a 3 digit number, thus padding the preceding empty spaces with zeros. %05.2f formats the number being printed to have a total length of 5 characters (including the decimal point), padding with 0 on the left, and two decimal places. So we get an output of 03.14. There is a lot more to formatting, but these are the essentials that we need to know. We have seen enough printf statements, so we are already familiar with the format of printf. lr_output_message is the equivalent of printf in LoadRunner. The output will be printed to the execution log in the Vugen window. So far, we have seen the relationship between a C program and a LoadRunner script, different data types and output formatting. Now we will try an example in Vugen. 10 For all exercises in this manual, create a new LoadRunner script means Case 1: If you are using LoadRunner 5.x In Vugen, select File -> New, and select General. This will give you an empty template. Case 2: If you are using LoadRunner 6.x In Vugen, select File -> New, and select C Template under General. This will give you an empty C template. All above examples can be cut and paste into an empty LoadRunner script. Exclude the ‘#include’ statements, and paste the contents of the main inside the Actions section of a empty LoadRunner script. Exercise 2.1 Create a new LoadRunner script in Vugen. Copy the following script into the actions section of the script. int a = 5; float x = 3.14; char c = „A?; lr_output_message(“The values are: a = %d, x = %f, c = %c”,a,x,c); Now run the vuser. This is what your script and execution log will look like. 11 Figure 1.2: Exercise in Data Types Make the following changes to the original program and run the vuser for each case. Explain the result wherever necessary. Undo your changes after each case to restore the program to its original state. a) Change a = 5 to a = 2200000000 b) Change a = %d to a = %05d and x = %f to x = %9.5f c) Change c = „A? to c = „A? + 1 d) Change c = %c to c = %d If you are new to C programming, here are the two most common mistakes you want to avoid: 1.C is case sensitive. Variable ‘x’ is not the same as ‘X’. 2.Each statement has to end with a semi-colon. 12 3. Control Flow In the last section, we have seen simple programs involving declaration of variable, assignment of values to the variable and output formatting. In this section, we will look at some basic constructs available in C to control the flow of a program. Two types of constructs are available in C 1. 1. Branching Constructs a. a. if b. b. switch 2. 2. Looping Constructs a. a. for b. b. while c. c. do while It is important to understand Boolean operators before we discuss any of the control flow constructs. Boolean Operators Te operators that are used to make decisions are called Boolean operators. They return Boolean values, i.e., the value is either true or false. In C, „0? is used to represent false and any non-zero number represents true. The following table gives the list of logical and relational operators: Symbol Meaning < LESS THAN <= LESS THAN OR EQUAL TO > GREATER THAN >= GREATER THAN OR EQUAL TO == EQUAL TO && AND || OR ! NOT Variables are joined by operators to form expressions. An expression has a Boolean value, either true or false. For example: if x=2 and y=3, the following are some expressions with their Boolean values 1. 1. (x < y) TRUE 2. 2. (x == y) FALSE 13 3. 3. (x+y >= 7) FALSE Compound Boolean statements can be constructed using logical operators. See the following table. Value1 refers to the first parenthesis in column 1 and Value2 refers to the second. This table is again based on x = 2 and y = 3. Expression Value1 Value2 Expression Value (x < y) && (y >= 0) TRUE TRUE TRUE (x > y) || (y >= 0) FALSE TRUE TRUE !x && (y > x) FALSE TRUE FALSE If Statements If statements have the following syntax: if (condition) { group1 of code } else { group2 of code } Note that it is not necessary to use an else. You can use if statements by themselves. Example: We want to write a program that takes your LoadRunner CPS score, and makes the following comments based on the score. Score less than 75: “Bad luck, try again!!” Score between 75 and 85: “Good Job!” Score above 85: “Excellent, keep up the good work!” This program should work in Vugen. Cut the following piece of code and paste it in the actions section of a new LoadRunner script. Run this vuser with different values for the variable MyCPSScore. int MyCPSScore = 80; if(MyCPSScore < 75) { lr_output_message(“>>>>>>>>>>> Bad luck, try again!!”); } else if((MyCPSScore >= 75) && (MyCPSScore <= 85)) { 14 lr_output_message(“>>>>>>>>>>> Good Job!”); } else if((MyCPSScore > 85) && (MyCPSScore <= 100)) { lr_output_message(“>>>>>>>>> Excellent, Keep up the good work!”); } else { lr_output_message(“>>>>>>>>>>> Invalid score!”); } ,It is not necessary to enclose the block of code corresponding to each if/else statement within { and } if the block consists of a single statement. Multiple statements need to be grouped. , You don?t need a semi-colon after an if statement. Switch Statement A switch statement is used to make a decision based on an integer value. The switch statement is a better way of writing a program when a series of if elses occurs. The general format for this is, switch ( expression ) { case value1: program statement; program statement; ...... break; case value2: program statement; program statement; ...... break; …………… …………… case valuen: program statement; ....... break; default: ....... 15 ....... break; } where expression can assume values of value1, value2 … valuen. The keyword break must be included at the end of each case statement. The default clause is optional, and is executed if none of the cases are met. The right brace at the end signifies the end of the case selections. Example: Lets say you are creating a LoadRunner web scripts at a customer site. The scripts should emulate purchase of 10 products from their website. The customer tells you that all products have equal probability of being purchased, meaning they are sold in equal numbers. And you have to run a test with 30 users. You can take two approaches. One is to create 10 different scripts, one each for purchasing each one of the 10 products. Run 3 vusers for each script to comply with the requirement that all products are bought equally. The other approach is to create a single script and use logic to select one of the 10 products such that the products are bought equally. We will take the second approach and use a switch statement to accomplish this. Before we get to the script, lookup the help on the function lr_whoami. This function returns the vuser number among other things. Also, we need to understand the „%? operator in C. The „%? operator gives the modulus of two numbers. So the value of (x % y) is the reminder on dividing x by y. For example, (10 % 3) is 1. (25 % 7) is 4. Now take a look at the script below. int Vuser,ProductNumber; lr_whoami(&Vuser, NULL, NULL); ProductNumber = Vuser%10 + 1; switch(ProductNumber) { case 1: /* In reality, this block here would contain the LR functions for buying product1. Since we don't have a real website, lets pretend with the message below */ lr_vuser_status_message("I am buying product1"); break; case 2: lr_vuser_status_message("I am buying product2"); break; case 3: 16 lr_vuser_status_message("I am buying product3"); break; case 4: lr_vuser_status_message("I am buying product4"); break; case 5: lr_vuser_status_message("I am buying product5"); break; case 6: lr_vuser_status_message("I am buying product6"); break; case 7: lr_vuser_status_message("I am buying product7"); break; case 8: lr_vuser_status_message("I am buying product8"); break; case 9: lr_vuser_status_message("I am buying product9"); break; case 10: lr_vuser_status_message("I am buying product10"); break; default: lr_vuser_status_message("invalid product %d",ProductNumber); } lr_think_time(100); Paste the above code in a new LoadRunner script and run 30 vusers through a Controller. In runtime settings for the script, select the „Replay thinktimes as recorded? option. Also make sure that your Vusers are numbered 1 through 30. Observe the Vusers window in the controller. You will notice that all each product is being bought by 3 vusers. Exercise 3.1 a) a) Run the above script in Vugen (Not Controller). Explain the result. b) b) Explain the statement ProductNumber = Vuser%10 + 1; c) c) In case 3, remove the break statement, save the script and run the scenario (not the script) again. Explain the results. For Loops The basic format of the for statement is, for( start condition; continue condition; re-evaluation ) { 17 program statements; } Example: In the earlier sections, we learnt that the characters in C have a corresponding integer value. In the following example, we will print numbers 60 to 100 and their corresponding character values. Actions() { int i; for(i=50;i<=100;i++) lr_output_message("%d = %c",i,i); return 0; } In the above example, observe the statement for(i=0;i<100;i++). The three segments of the for statement are: start condition i=50 (value of i starts at 50) continue condition i<= 100 (the loop continues as long as i is less than or equal to 100) re-evaluation i++ (increment i by 1 after each iteration) In the lr_output_message statement, notice that we are printing the value of „i? twice, but using different formatting. The first format is %d and the second is %c. So the output will consist of an integer value, and the corresponding character value. The output of the above example would be as follows: Virtual User Script started Running Vuser... Starting iteration 1. Actions.c(7):50 = 2 Actions.c(7):51 = 3 Actions.c(7):52 = 4 Actions.c(7):53 = 5 Actions.c(7):54 = 6 Actions.c(7):55 = 7 Actions.c(7):56 = 8 Actions.c(7):57 = 9 Actions.c(7):58 = : Actions.c(7):59 = ; Actions.c(7):60 = < Actions.c(7):61 = = Actions.c(7):62 = > Actions.c(7):63 = ? Actions.c(7):64 = @ Actions.c(7):65 = A Actions.c(7):66 = B 18 Actions.c(7):67 = C Actions.c(7):68 = D Actions.c(7):69 = E ……………… ……………… ……………… Actions.c(7):95 = _ Actions.c(7):96 = ` Actions.c(7):97 = a Actions.c(7):98 = b Actions.c(7):99 = c Actions.c(7):100 = d Ending iteration 1. Ending Vuser... Vuser Terminated. for loops can also be nested. This means placing a for loop inside another for loop. Try the following program in LoadRunner and explain the output. Actions() { int i; int j; for(i=1;i<=3;i++) { for(j=1;j<=3;j++) { lr_output_message("i=%d, j=%d",i,j); } lr_output_message("End of j loop"); } lr_output_message("End of i loop"); return 0; } 19 While The while has the form: while (expression) { statement1 statement2 ………… } The above block of statements is executed continuously as long as the expression in the while statement is true. A simple example: Actions() { int i=0; while(i < 5) lr_output_message("Current Value of i = %d",i++); return 0; } In the above example, i is set to an initial value of 0. The lr_output_message statement is executed and the value of i is incremented by 1 (using i++). Now the value of i is 1. So it goes back in the loop, evaluates the expression „i < 5? in the while statement. Since i < 5 is true, it executes the lr_output_message statement again, and increments the value of i. This continues till the expression „i<5? is false. The following would be the output of the above program. Virtual User Script started Running Vuser... Starting iteration 1. Actions.c(6):Current Value of i = 0 Actions.c(6):Current Value of i = 1 Actions.c(6):Current Value of i = 2 Actions.c(6):Current Value of i = 3 Actions.c(6):Current Value of i = 4 Ending iteration 1. Ending Vuser... Vuser Terminated 20 Note that we had only one statement in the while loop. You can have multiple statements enclosed by braces. How do we choose between a while and a for loop? A for loop is used when we know the exact number of iterations that we want to run. If you want to print numbers from 0 to 9, you can use a for loop for(i=0;i<=9;i++). while loops are used when the number of iterations is not definite. The above example for a while loop could have been written using a for statement. Do While A do while loop is similar to a while loop, except that the expression is evaluated at the end of the block of statements in the loop. do { statement1 statement2 ………… } while (expression); break and continue C provides two commands to control how we loop: , , break -- exit form loop or switch. This applies only to for/while loops. To break out of a LoadRunner iteration, use exit(-1); , , continue -- skip 1 iteration of loop. This applies only to for/while. To continue to the next iteration in LoadRunner iterations, use return 0. You will find these very useful when you have to conditionally break out of a LoadRunner iteration or exit out of a script. The following example should illustrate the use of exit and continue in LoadRunner. // Global variable count int count=0; // Global variable count int count=0; Actions() { // Increment count // count++; 21 // If count is equal to 10, exit the script // if(count == 10) exit(-1); // If count is even, skip the current iteration // and continue with the next iteration // if(count%2 == 0) return 0; lr_output_message(">>>>>>>>>>>>>>>>>>>>>> %d",count); return 0; } Exercise 3.2 a) a) You invest $10,000 in a special account that pays 8% interest at the end of each year on the beginning balance of the year. You decide to take your investment out as soon as it doubles. Write a program that will print out the year, beginning balance, interest gained for the year and the ending balance for the year. This program should stop as soon as the ending balance reaches $20,000. All dollar amounts should be printed to a precision of 2 decimals. Here is what a sample output might look like: Virtual User Script started Running Vuser... Starting iteration 1. Actions.c(18):Year = 1, Beginning Balance = 10000.00, Interest = 1000.00, Ending Balance = 11000.00 Actions.c(18):Year = 2, Beginning Balance = 11000.00, Interest = 1100.00, Ending Balance = 12100.00 Actions.c(18):Year = 3, Beginning Balance = 12100.00, Interest = 1210.00, Ending Balance = 13310.00 Actions.c(18):Year = 4, Beginning Balance = 13310.00, Interest = 1331.00, Ending Balance = 14641.00 Actions.c(18):Year = 5, Beginning Balance = 14641.00, Interest = 1464.10, Ending Balance = 16105.10 Actions.c(18):Year = 6, Beginning Balance = 16105.10, Interest = 1610.51, Ending Balance = 17715.61 Actions.c(18):Year = 7, Beginning Balance = 17715.61, Interest = 1771.56, Ending Balance = 19487.17 Actions.c(18):Year = 8, Beginning Balance = 19487.17, Interest = 1948.72, Ending Balance = 21435.89 Ending iteration 1. Ending Vuser... The above output was created for an interest rate of 10%. 22 Now, lets say you have the same account as in the previous problem, except that b) b) you choose to keep your investment for a period of 10 years. Write a program that will output the results as in the previous problem, except that this will always be for 10 years. c) c) What looping constructs did you use in the above two problems, and why? d) d) Using the break and/or continue statements, how can you solve problem a with a for loop? The ? operator The ? (ternary condition) operator is a more efficient form for expressing simple if statements. It has the following form: expression1 ? expression2: expression3 It simply states: if expression1 is true then expression2 else expression3 For example to assign the maximum of a and b to z: z = (a>b) ? a : b; which is the same as: if (a>b) z = a; else z=b; 23 4. Arrays and Strings Arrays Arrays are used to store a list of similar data types for easy access. For example, if we have 5 numbers that we need to find the sum and average, it is easier to declare and operate with an array than to declare 5 different variables. Example: Given 5 numbers, find their sum and average. Solution 1: Without arrays Actions() { int Num1 = 5; int Num2 = 12; int Num3 = 7; int Num4 = 22; int Num5 = 4; int Sum, Average; Sum = Num1+Num2+Num3+Num4+Num5; Average = Sum/5; lr_output_message("Sum = %d, Average = %d",Sum,Average); return 0; } Solution 2: Using Arrays Actions() { int MyArray[] = {5,12,7,22,4}; int Sum, Average, i; for(i=0;i<5;i++) Sum+= MyArray[i]; Average = Sum/5; lr_output_message("Sum = %d, Average = %d",Sum,Average); return 0; } 24 In the solution using arrays, the numbers have been assigned to MyArray using the statement int MyArray[] = {5,12,7,22,4}; This will assign the values such that MyArray[0] = 5; MyArray[1] = 12; MyArray[2] = 7; MyArray[3] = 22; MyArray[4] = 4; The above is also a legal syntax for assigning values for individual elements of an array. Now, accessing the individual elements of the array is easy because we can use a for loop to traverse through the array. The statement Sum+=MyArray[i] is equivalent to saying Sum = Sum + MyArray[i] Strings Strings in C are nothing but character arrays. Consider the following example: Actions() { int i; char MyArray[] = {'M','e','r','c','u','r','y'}; /* Printing one char at a time */ for(i=0;i<7;i++) lr_output_message(">>>>>> %c",MyArray[i]); /* Printing the whole string */ lr_output_message("String = %s",MyArray); return 0; } In this example, we declared a char array, and assigned characters to each individual element. (Characters are enclosed in single quotes while strings are enclosed in double quotes). So the above string could have been assigned using: char MyArray[] = “Mercury”; 25 Since a group of characters put together form a string, the above array can also be considered as a string. The first output statement in the for loop outputs each character of the string. Notice that the „%c? format is used and one element of the array is printed at a time. The second output statement uses „%s? formatting (%s stands for a string) and prints the whole string. The following will be the output of the above program: Virtual User Script started Running Vuser... Starting iteration 1. Actions.c(7):>>>>>> M Actions.c(7):>>>>>> e Actions.c(7):>>>>>> r Actions.c(7):>>>>>> c Actions.c(7):>>>>>> u Actions.c(7):>>>>>> r Actions.c(7):>>>>>> y Actions.c(9):String = Mercury Ending iteration 1. Ending Vuser... Note that in the above example, we assigned the value of the string using char MyArray[] = {'M','e','r','c','u','r','y'}; But you may not always know the string/array-contents in advance like the above two examples. In that case, the array will have to be declared in advance with a particular size. For example, lets say you capture the first and last name of a person in a char array from a database query in your script. You don?t know the size of the name in advance. In that case, you declare a string of size larger than required and assign the value later. char NameArray[20]; ……………… ……………… sprintf(NameArray,"Joe Shmo"); We use the sprintf function to print a formatted string into a char array. In the above example, the array NameArray contains the string “Joe Shmo” in the first 8 elements 26 (including one space). C uses a special character „\0? to mark the end of a string to accommodate variable length strings like this. So the above string would be contained in NameArray as follows: NameArray J o e S h m o \0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 When the above string is printed, the program knows to stop at the eighth element in the string because it is an end-of-string character. 27 Exercise 4.1 a) Write a program that takes in your first and last name separated by a space, and prints them out separately. You program should start like this: Actions() { char MyName[] = "Jim Morrison"; …………… // your code goes here …………… } and the output should look like this: Running Vuser... Starting iteration 1. Actions.c(17):First Name: Jim Actions.c(24):Last Name: Morrison Ending iteration 1. Ending Vuser... Vuser Terminated. Hints: Use a do while loop to read the MyName array one character at a time and store these characters into a temporary array (string). When you encounter the blank space between the first and last names, print out the temporary string. This will be the first name. Now start storing the rest of the string into the temporary array again from the beginning, till you encounter the end-of-string character. Now this temporary array will form the last name. Remember that the expressions in while and if statements can be compounded using logical operators discussed earlier. String Manipulation strcpy is used to copy one string into another. strcat is used to add one string to the end of another. strcmp compares two strings and returns 0 if both strings are identical. atoi converts an ASCII string to an integer. itoa converts an integer to an ascii string for a given base. Syntax: strcpy(destination_string, source_string); strcat(string_that_gets_appended, string_that_is_appended); atoi(string_to_convert_to_int); //returns the integer value itoa(integer_to_conver_to_string, destination_string, base); // base is 10 strcmp(string1, string2); // returns 0 if both strings are equal 28 The following example illustrates all of the above functions. Execute the script below and observe the results. Actions() { char MyString1[20] = ""; char MyString2[20] = ""; char MyString3[20] = "Mercury2"; char Cstring[10] = "12345"; int Cint; // MyString1 is empty // lr_output_message(">>>>>>>>>> MyString1 = %s",MyString1); // copy "Mercury1" into MyString1 // strcpy(MyString1,"Mercury1"); // Now MyString1 contains "Mercury1" // lr_output_message(">>>>>>>>>> MyString1 = %s",MyString1); // Copy MyString3 into MyString2 // lr_output_message(">>>>>>>>>> MyString2 = %s",MyString2); strcpy(MyString2,MyString3); lr_output_message(">>>>>>>>>> MyString2 = %s",MyString2); // Catenate MyString2 to MyString1 // strcat(MyString1,MyString2); lr_output_message(">>>>>>>>>> MyString1 = %s",MyString1); // Cstring is converted to integer Cint // lr_output_message(">>>>>>>>>> Cstring = %s",Cstring); Cint = atoi(Cstring); lr_output_message(">>>>>>>>>> Cint = %d",Cint); // Cint is converted to string Cint = 100; itoa(Cint,Cstring,10); lr_output_message(">>>>>>>>>> Cstring = %s",Cstring); return 0; } Multi-Dimensional Arrays 29 We have seen single dimensional arrays in the previous sections. A single dimensional array consists of one row of elements. A multi-dimensional array will have more than one row and may also have multiple layers. Consider the following example: int MyArray[] = {1,2,3}; is equivalent to MyArray 1 2 3 0 1 2 int MyArray[3][3] = { {1,2,3}, {4,5,6}, {7,8,9} }; is equivalent to 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9 This means MyArray[0][0] = 1; MyArray[0][1] = 2; ………… ………… MyArray[2][1] = 8; MyArray[2][2] = 9; Two dimensional character arrays are handy for storing a list of strings. Consider the following example: Actions() { char MyArray[5][20]={"Doors","Led Zepplin","Grateful Dead", "Bob Dylan","Police"}; int i; // // We declared 5 rows of characters. // Each row is a string in itself; // So each row can be printed like a regular string. 30 // for(i=0;i<5;i++) lr_output_message("String %d: %s",i,MyArray[i]); return 0; } The declaration of the array above is equivalent to: MyArray 0 D o o r s \0 1 L e d Z e p p l i n \0 2 G r a t e f u l D e a d \0 3 B o b D y l a n \0 4 P o l i c e \0 31 The output for the above program would look like this: Virtual User Script started Running Vuser... Starting iteration 1. Actions.c(14):String 0: Doors Actions.c(14):String 1: Led Zepplin Actions.c(14):String 2: Grateful Dead Actions.c(14):String 3: Bob Dylan Actions.c(14):String 4: Police Ending iteration 1. Ending Vuser... Vuser Terminated. 32 5. File Processing When data is stored in variable, it is lost as soon as the program terminates. In some instances, we may need the data after the program terminates. We can read/write data to a text file using file-processing functions in C. Consider the case when you are testing a banking application using LoadRunner. You create new loan numbers using a Vugen script. You may need these loan numbers after the test so that you can use them in a different script (maybe for load processing). In this case, you will have to write the load numbers to a text file. File Declaration In C, file is a data type in itself. It is declared as a pointer. FILE *MyFile; LoadRunner does not support the FILE data type. So we can declare the file as an integer type. int MyFile; File Opening The above commands just declare a file. Files have to be opened before you can read/write to them. In C, you use the following command to open a new file. FILE *MyFile; MyFile = fopen(“C:\\temp\\loans.txt”,”w”); // In C, not LoadRunner The first argument is the path to the file that you want to create. The second argument specifies the mode in which you want to create the file. The follow modes are used often: “w” - Write, when you have to write to a file. If the file already exists, it is overwritten. If it does not exist, a new file by the name specified in the first argument is created. “r” – Read, when you want toread from a file. The file should already exist. “a” – Append, when you want to add data to the end of an existing file. “rw” – Read and Write. 33 The function fopen returns a pointer to a FILE data type. Since LoadRunner does not support FILE data type, the returned value has to be converted to an int. Conversion of one data type to another is referred to as type-casting. int MyFile; MyFile =(int) fopen(“C:\\temp\\loans.txt”,”w”); // In LoadRunner Note that the path to the file contains a „\\? instead of a „\?. This is because „\? is a control character in C and has a special meaning. Hence the „\\?, which will be interpreted as a „\?. You will have to use the full path to the file in fopen unless the file is in the same directory as the script (or if it is in the search path of the program). It would suffice to say MyFile = fopen(“loans.txt”,”r”); if the file loans.txt is in the same directory as the script. File Reading fscanf function is used to read from a file. The function syntax is: int MyFile; int LoanNumber; MyFile = fopen(“C:\\temp\\loans.txt”,”r”); fscanf(MyFile,”%d”, &LoanNumber); Note that MyFile, which is the file pointer (not really a pointer in LoadRunner), is being used instead of the actual file. All file processing functions use the file pointer, not the actual file name. Exercise 5.1 Copy the following numbers into a notepad and save it as c:\temp\loans.txt 11111 22222 33333 44444 55555 Now run the following program and observer the results. Actions() { int MyFile; int LoanNumber,i; // Assigning the file path to a string char FileName[80] = "C:\\temp\\loans.txt"; 34 // Opening the file // Note the use of variable to replace the file path // MyFile = (int)fopen(FileName,"r"); // Reading and printing one loan number at a time for(i=1;i<=5;i++) { fscanf(MyFile,"%d", &LoanNumber); lr_output_message("Loan Number %d: %d",i,LoanNumber); } fclose(MyFile); return 0; } When a file is opened, the file pointer is positioned at the beginning of the file. After each read, the pointer repositions itself for the next element. That?s how the above program reads the next element automatically. a) a) Change the for loop to for(i=1;i<=7;i++) and rerun the above program. Explain the results. b) b) In the above file loans.txt, we know the total number of loans to be read was 5. So we were able to use a for loop. If the number of loan numbers was unknown, and you were to read the loan numbers until the end of file is reached, you will have to use a while loop. A useful function in this case is feof. feof(MyFile) will return a value 0 is the end offile is not reached, and will return a non-zero value if the end is reached. You can use this as your conditional expression in the while statement. Now add a few more numbers to the loans.txt file, and modify the above program using a while loop to read and print the loan numbers till the end of file. So your while statement will look like this while(feof(MyFile) == 0) NOTE: If you have empty lines at the end of the text file, feof might treat them as part of the file. File Writing fprintf function is used to write to a file. fprintf has the syntax int MyFile; char Name[] = “John Doe”; MyFile = fopen(“C:\\temp\\loans.txt”,”w”); // note that “w” is used to write fscanf(MyFile,”%s”, Name); // note that we are printing a string here The first argument is the file pointer, second argument is the format you want to print, and the third (optional) argument is the variable that you used in the format (%c, %d, %s, etc.). Run the following program: 35 Actions() { int MyFile; char Name[] = "John Doe"; MyFile = fopen("C:\\temp\\names.txt","w"); // note that "w" is used to write fprintf(MyFile,"%s", Name); // note that we are printing a string here fclose(MyFile); return 0; } Now open the file c:\temp\names.txt and see if the name John Doe appears in it. 36 Exercise 5.2 Copy the following names into a text file and save it as c:\temp\data.txt BlackDog RockandRoll TheBattleofEvermore StairwaytoHeaven MistyMountainHop Write a program to read these names and print them into a new file c:\temp\data2.txt, each name twice. data2.txt should look like this: BlackDog BlackDog RockandRoll RockandRoll TheBattleofEvermore The BattleofEvermore StairwaytoHeaven StairwaytoHeaven MistyMountainHop MistyMountainHop In this program, do not use a for/while loop to read the file, but use the iterations built into LoadRunner. The program should not be set to 5 iterations, it should work for a variable number of names in data.txt. In a for/while loop, we use expressions to exit out of the loop. Use the return and exit statements introduced in chapter 3 to accomplish the same in LoadRunner iterations. In this case, since you are going to traverse through the Actions section of the script multiple times, you cannot open/close the file multiple times. So the files will have to be declared globally, opened in vuser_init, read and written in Actions, and closed in vuser_end. Use “\n” to print a new line character. 37 6. 6. Functions User-defined Functions User-defined functions can be created in C to do specific tasks. By proper planning, these functions can be created to be reusable. This will save you the need to repeat the code every time you need to do that specific task. Function syntax in C is: data_type FunctionName(data_type parameter_1, data_type parameter_2………); Observe the following program: float average_function(int a, int b, int c) { // This function calculates the average of // three numbers and returns the value float AverageValue=0.0; // calculate the average of the incoming values // AverageValue = (a+b+c)/3; // return the average to the calling function return(AverageValue); } Actions() { float X; X = average_function(10,20,30); lr_output_message(">>>>>> The average is %.2f",X); X = average_function(20,30,40); lr_output_message(">>>>>> The average is %.2f",X); return 0; } The above program contains a function called average_function which calculates the average of three integers and returns the result as a floating point number. As you can see, the code for the function has been included on top of the Actions section. This is called function declaration and definition. Once a function is declared and defined, it can be called any number of times from other functions, as long as it is accessible from those other functions. 38 In this case, we called the function average_function in the Actions section using X = average_function(10,20,30); When the program reaches this point, the control of the program passes to the function average_function with the values 10, 20 and 30. Now, in the function, a, b and c will assume the values 10, 20 and 30. Since the function calculates the average of a, b, and c and returns the average value, X will be assigned this average value passed back by the function. lr_output_message will print the average out. The next time we call this function in Actions, we are passing values 20, 30 and 40. So X will now have the average of these values. The following will be the output of the above program: Running Vuser... [MsgId: MMSG-15966] Starting iteration 1. [MsgId: MMSG-15970] Actions.c(22):>>>>>> The average is 20.00 [MsgId: MMSG-17999] Actions.c(25):>>>>>> The average is 30.00 [MsgId: MMSG-17999] Ending iteration 1. [MsgId: MMSG-15967] Ending Vuser... [MsgId: MMSG-15968] Vuser Terminated. [MsgId: MMSG-15965] So by writing a function, we did not have to repeat the code for calculating the average of three numbers. We just called the function again. This is a trivial example, but we could accomplish some complex tasks using functions. Just like variables, functions also have a scope of definition. This same function could have been defined inside Actions, but then it would be accessible only to the Actions section. It is a better idea to put your function definitions on top of the vuser_init section, so that they can be called from any section within the script. In the above example, we passed integers to a function. Similarly, you can send other data types and arrays to a function. Recollect exercise 4.1, where we wrote a program to split a given name into the first and last names. Imagine that you have to do it multiple times inside your script. It makes sense to create a function that splits the name and call that function multiple time, rather than duplicating the code. Exercise 6.1 Write a function split_function that takes in a first and last name separated by a space, and prints them out separately. You should be able to make minor modifications to the solution of exercise 4.1 to accomplish this. You Actions section should look like this void split_function(char MyName[]) { // your code goes here 39 return; } Actions() { split_function(“Jim Morrison”); split_function(“John Doe”); split_function(“Joe Shmo”); return 0; } and the output should look like this: Running Vuser... [MsgId: MMSG-15966] Starting iteration 1. [MsgId: MMSG-15970] Actions.c(33):First Name: Jim [MsgId: MMSG-17999] Actions.c(46):Last Name: Morrison [MsgId: MMSG-17999] Actions.c(33):First Name: John [MsgId: MMSG-17999] Actions.c(46):Last Name: Doe [MsgId: MMSG-17999] Actions.c(33):First Name: Joe [MsgId: MMSG-17999] Actions.c(46):Last Name: Shmo [MsgId: MMSG-17999] Ending iteration 1. [MsgId: MMSG-15967] Ending Vuser... [MsgId: MMSG-15968] Vuser Terminated. [MsgId: MMSG-15965]Vuser Terminated. Since split_function does not return any value, it definition is preceded by void. Similarly, there could be functions that do not need any arguments to be passed, in which case they would have a format function_name(void). Also note that char MyName[] has been passed to the function, so it need not be declared inside the function again. Include Files Lets say you have 5 functions that you want to use in your script. You could include all these functions on top of your vuser_init section, but it might make the script look messy, and you also run the risk of these functions being modified accidentally. You can put all these functions in a text file, and just add one line on top of your vuser_init section to include the file with functions during runtime. Create a new LoadRunner 6.0 web script in Vugen. If you notice the top of the vuser_init section, you will see #include "as_web.h". as_web.h is a file that contains all the LoadRunner functions specific to web. So they are being included on top of your script. Such files are referred to as header files, and hence the extension „.h?. Also note that these functions need not be user-written; you can also cut and paste recorded LoadRunner script into a function. Exercise 6.2 40 Follow the steps below and observe how it works: i. i. Save the script that you created for exercise 6.1 with a different name, say script_6_2. ii. ii. Cut (not copy) the function split_function from above the Actions section in this script and paste it in a notepad and save this file as “MyHeader.h” in c:\temp directory. (Make sure that you are not saving it as MyHeader.h.txt by mistake) iii. iii. Now, in script_6_2, include the line - #include “c:\\temp\\MyHeader.h” - on top of the vuser_init section. iv. iv. Run the program, and the split calls in the Actions section should still work. In this case, we had to specify the full path of the header file in #include. If the header file was saved in either the script directory itself or in C:\Program Files\Mercury Interactive\LoadRunner\include, we will just need the name of the file. 41 7. Miscellaneous Functions System The system function call is very useful when you have to execute a command at the DOS prompt during a script execution. Syntax: system(command_string); Create a file temp.txt in C:\temp and try the following script: Actions() { system("del c:\\temp\\temp.txt"); return 0; } The temp.txt file should get deleted. Random Numbers You may have to generate random numbers in your scripts to simulate some random events. The need for this has been reduced these days because LoadRunner accommodates random think times in version 6.x. But it is useful to have a function that gives you random numbers. rand is a function that can generate pseudo-random numbers. The randomness of these numbers (or the lack thereof), is dependent on the seed used to generate the random number. A very common technique is to seed the random generator using the time of the day. The function used for seeding is srand. Run the following script twice and compare the results. You will see that the sequence of numbers generated is the same on both occasions. This is because there was no seed. Actions() { int i; // srand(time(NULL)); for(i=0;i<10;i++) lr_output_message(">>>>>>>>>> Random Number: %d",rand()); } 42 Now, un-comment the statement srand(time(NULL)), and run the script twice. You will see that the sequence of numbers generated is different. The function rand returns integers in the range 0 to MAX_RAND, where MAX_RAND is system dependent. In NT, this number is 32767. It is more useful to have a function that returns a random number within a range that you can specify. Here is a function that can generate a random number within a given range: int random_number(int LowerBound, int UpperBound) { return((int)((float)(UpperBound - LowerBound + 1)*rand()/32770.0) + LowerBound); } Paste the above function on top of your vuser_init, and call the function inside the Actions section as follows: Actions() { int i; srand(time(NULL)); for(i=0;i<100;i++) lr_output_message(">>>>>>>>>> Random Number,%d,", random_number(1,10)); } Here, the user-defined function is called from the Actions section as random_number(a,b); and the function returns a random between a and b, including both. srand is used to set the seed at the beginning. 43 Solutions Exercise 2.1 a) a) The value of a will print incorrectly. This is because you exceeded the range of permitted values for int. b) b) Will print “The values are: a = 00005, x = 003.14000, c = A” c) c) Will print c = B. This is because we added 1 to c, whose initial value was „A?. As mention in that section, characters are represented by integers internally. Since the value of „A? is 65, the initial value of c was 65. Adding 1 makes it 66, which is equivalent to „B?. d) d) Will print c = 65. Here, we changed the formatting to print an integer, so it printed the equivalent integer value of „A?. 44 Exercise 3.1 a) a) The output will say “Invalid Product 0”. This is because, lr_whoami command returns a valid vuser number only when run thru the Controller. When you run the script in Vugen, it returns a value of „-1?. This will make the ProductNumber = 0, which is a defined case in the script. So it goes to the default code, which prints the message “Invalid Product 0”. b) b) The requirement for this test was that each product had to be bought with equal probability by all 30 vusers. Now, since the lr_whoami command returns values 1 thru 30 for the 30 vusers, the following is what will happen: Value returned by Vuser%10 ProductNumber = lr_whoami (Vuser)Vuser%10 + 1 1 1 2 2 2 3 3 3 4 4 4 5 ….. …. …. ….. ….. …. 10 0 1 11 1 2 12 2 3 …. …. ….. …. …. …. 30 0 1 From the above table, you can see that Vuser 1 will buy product 2, Vuser 2 will buy product 3.. and so on and Vuser 10 will buy product 1. c) c) You will see that product 4 is being bought by 6 vusers instead of 3. This is because the control will not break out of case 3 because of the missing break statement. So the 3 vusers who bought product 3, will go into case 4 and buy product 4. So we see a total of 6, original 3 and the carryover 3 vusers, who are buying product 4. 45 Exercise 3.2 a) Actions() { int Year=1; float Interest=0.00; float InterestRate = 8.0; float InitialAmount = 10000.00; float BeginningBalance; float EndingBalance; /* Initial amount will be the beginning balance for the first year */ BeginningBalance = InitialAmount; do { Interest = BeginningBalance * InterestRate/100; EndingBalance = BeginningBalance + Interest; lr_output_message("Year = %d, Beginning Balance = %.2f," " Interest = %.2f, Ending Balance = %.2f", Year++,BeginningBalance,Interest,EndingBalance); BeginningBalance = EndingBalance; } while(EndingBalance <= 20000.00); return 0; } b) Actions() { int Year=1; float Interest=0.00; float InterestRate = 8.0; float InitialAmount = 10000.00; float BeginningBalance; float EndingBalance; /* Initial amount will be the beginning balance for the first year */ BeginningBalance = InitialAmount; for(Year=1; Year<=5; Year++) { Interest = BeginningBalance * InterestRate/100; EndingBalance = BeginningBalance + Interest; lr_output_message("Year = %d, Beginning Balance = %.2f," " Interest = %.2f, Ending Balance = %.2f", 46 Year,BeginningBalance,Interest,EndingBalance); BeginningBalance = EndingBalance; } return 0; } c) c) In problem a, the number of years it would take to double the initial investment was not known. So we used a while loop. In problem b, we knew that the investment period was 10 years, so we used a for loop. d) d) Use a for loop that has an infinite (very large) exit condition, and break out of the loop when the ending balance is twice the initial amount. Exercise 4.1 a) Actions() { char MyName[] = "Jim Morrison"; char TempArray[20], TempChar; int i=0,j=0; do { // // Assigning the current character to a temporary char // Increment i for the next character // TempChar = MyName[i++]; // // If the current char is not a blank or end-of-string // then put it in a temporary string called TempArray // if(TempChar != ' ' && TempChar != '\0') TempArray[j++] = TempChar; // // If it is a blank, it means the end of first name // so put a end-of-string character on the TempArray // and print it out. // Since we will use the TempArray to hold the last name // reset j to 0. // else if(TempChar == ' ') { TempArray[j++] = '\0'; lr_output_message("First Name: %s",TempArray); j=0; } 47 // // If the current character is '\0', it means // the end of the last name. So put a '\0' in the // TempArray and print it out // else if(TempChar == '\0') { TempArray[j++] = '\0'; lr_output_message("Last Name: %s",TempArray); } // Exit the while loop once '\0' character is encountered. } while(TempChar != '\0'); return 0; } Exercise 5.1 a) a) The number 55555 will be printed thrice. This is because the file pointer could not advance beyond the last string, but the loop had 7 iterations. So it ththprinted the last value contained in the variable in the 6 and 7 iterations. b) b) Program: Actions() { int MyFile; int LoanNumber,i; // Assigning the file path to a string char FileName[80] = "C:\\temp\\loans.txt"; // Opening the file // Note the use of variable to replace the file path // MyFile = (int)fopen(FileName,"r"); // Reading and printing one loan number at a time while(feof(MyFile) == 0) { fscanf(MyFile,"%d", &LoanNumber); lr_output_message("Loan Number %d: %d",i,LoanNumber); } fclose(MyFile); return 0; } 48 Exercise 5.2 vuser_init: int MyFile1; int MyFile2; // Assigning the file path to a string char FileName1[20] = "C:\\temp\\data.txt"; char FileName2[20] = "C:\\temp\\data2.txt"; vuser_init() { // Opening the file data.txt to read // Note the use of variable to replace the file path // MyFile1 = (int)fopen(FileName1,"r"); // Opening the file data2.txt to write // Note that the mode changed to "w" // MyFile2 = (int)fopen(FileName2,"w"); return 0; } Actions Actions() { char Name[80]=""; fscanf(MyFile1,"%s",Name); fprintf(MyFile2,"%s\n",Name); fprintf(MyFile2,"%s\n",Name); if(feof(MyFile1) != 0) exit(-1); return 0; } vuser_end vuser_end vuser_end() { fclose(MyFile1); fclose(MyFile2); return 0; } 49 Exercise 6.1 void split_name(char MyName[]) { char TempArray[20], TempChar; int i=0,j=0; do { // // Assigning the current character to a temporary char // Increment i for the next character // TempChar = MyName[i++]; // // If the current char is not a blank or end-of-string // then put it in a temporary string called TempArray // if(TempChar != ' ' && TempChar != '\0') TempArray[j++] = TempChar; // // If it is a blank, it means the end of first name // so put a end-of-string character on the TempArray // and print it out. // Since we will use the TempArray to hold the last name // reset j to 0. // else if(TempChar == ' ') { TempArray[j++] = '\0'; lr_output_message("First Name: %s",TempArray); j=0; } // // If the current character is '\0', it means // the end of the last name. So put a '\0' in the // TempArray and print it out // else if(TempChar == '\0') { TempArray[j++] = '\0'; lr_output_message("Last Name: %s",TempArray); } // Exit the while loop once '\0' character is encountered. } while(TempChar != '\0'); return; } 50
本文档为【General C Programming Examples】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_597436
暂无简介~
格式:doc
大小:209KB
软件:Word
页数:74
分类:
上传时间:2018-03-21
浏览量:11