Lab Manual 09-12
Lab Manual 09-12
STRINGS
Lab Objectives:
By now, you have learned how to declare achar variable to hold characters. ; You might also have
learned that a string (like a person's first or last name) in C++ can simply be represented by a null-
terminated sequence of characters stored in a char array. These days you can use the string type
for strings. In the bad old days, before circa 1994, you had to use character arrays, because there
was no native string type in C++ most implementations. There is still no string type in C. A string,
represented as a character array, is called a "C string". Here's a quick little review of declaring
and initializing C strings.
char s1[8];
Note: You cannot assign the value of a C string after the declaration
as you do with other simple variable assignments.
i.e. s1 = "one"; <- WRONG
C++ supports a wide range of C string manipulation functions. Following are some of them:
1.1 strcpy
Use this function if you would like to copy one string to another string.
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
char Original[30] = "I am the original!";
char Copy[30] = "I am the copy!";
strcpy(Copy, Original);
cout << "After strcpy(): " << endl;
cout << "Original = " << Original << endl;
cout << "Copy = " << Copy << endl;
return 0;
Before strcpy():
Original = I am the original!
Copy = I am the copy!
After strcpy():
Original = I am the original!
Copy = I am the original!
1.2 strlen
Use this function if you would like to know the length of a string.
3
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
char String1[30]= "I am the string!";
return 0;
STRING CLASS
C String is one of the two ways that you can manipulate strings in C++. The other way is through
the string class. This allows strings to be represented as objects in C++. The string class gives
you strings of unbounded length because the string space is allocated at run-time. Compare
this to C Strings where the finite string length of char array variables is defined at compile
time.
Moreover, assignment, comparison, and concatenation of strings using the string class is
arguably easier than using C Strings. However, you'll still see C String code around in older
programs so it's best to know both.
Why, you may ask, do we need the string class when we already have C string? Here is why:
null terminated strings (C strings) cannot be manipulated by any of the standard C++
operators. Nor can they take part in normal C++ expressions. For example, consider this
fragment:
s1 = "one"; // error
s2 = "two"; // error
s3 = "three"; //error
As the comments show, in C++, it not possible to use the assignment operator to give a character
array a new value. To do this, you need to use the strcpy function that was discussed above:
4
strcpy(s1, "one");
strcpy(s2, "two");
strcpy(s3, "three");
There are also other reasons for using strings. For example, the null-terminated C String does
not check if the array is out of bound and that contributes to many string problems encountered
by C++ programmers, experienced and inexperienced alike.
Following is an example showing you how to use the string class to manipulate strings. The
example gives you a feeling of how string objects work, which means you do not need to
remember how it really works.
int main()
{
string str1("This is a test");
string str2("ABCDEFG");
// demonstrate length()
cout << "Length of str1 is: " << str1.length() << endl;
return 0;
}
Initial strings:
str1: This is a test
str2: ABCDEFG
Example 2:
This example shows how to traverse an array using pointers:
#include <iostream>
using namespace std;
int main() {
int *ip;
int arr[] = { 10, 34, 13, 76, 5, 46 };
ip = arr;
for (int x = 0; x < 6; x++) {
cout << *ip << endl;
ip++;
}
return 0;
}
A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. The general form of a pointer
variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of
the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Following are the valid pointer declaration −
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.
There are few important operations, which we will do with the pointers very frequently. (a) We
define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the
value at the address available in the pointer variable. This is done by using unary operator * that
returns the value of the variable located at the address specified by its operand. Following
2
Example
#include <iostream>
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
Question 1
#include <iostream>
using namespace std;
int main()
{
int a = 32, *ptr = &a;
char ch = 'A', &cho = ch;
cho += a;
*ptr += ch;
cout << a << ", " << ch << endl;
return 0;
}
Solution
Answer: c. 129, a
1
Explanation: The “ptr” variable is a pointer which holds the address of variable “a”. And “*ptr”
returns the value of “a” variable. “cho” is a reference variable to “ch”. So any change made to “cho”
will be reflected to “ch”. As such, when “cho” is increased by 32, it adds to the ASCII value of
“A”(which is 65), and this results to 97 which is the ASCII value of “a”(from the alphabet). So this
“a” gets stored in “ch”. As for when “*ptr” is incremented by “ch”, it gives value 97+32=129.
STRUCTURES
STRUCTURES
C/C++ arrays allow you to define variables that combine several data items of the same kind, but
structure is another user defined data type which allows you to combine data items of different
kinds.
Structures are used to represent a record, suppose you want to keep track of your books in a library.
You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
DEFINING A STRUCTURE
To define a structure, you must use the struct statement. The struct statement defines a new data type,
with more than one member, for your program. The format of the struct statement is this −
The structure tag is optional and each member definition is a normal variable definition, such as int
i; or float f; or any other valid variable definition. At the end of the structure's definition, before the
final semicolon, you can specify one or more structure variables but it is optional.
Here is the way you would declare the Book structure −
struct Books {
char title[50]; char author[50]; char subject[100]; int book_id;
} book;
2
int main() {
struct Books Book1; // Declare Book1 of type Book struct Books Book2; // Declare Book2
of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming"); strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming"); Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom"); Book2.book_id = 6495700;
// Print Book1 info
cout << "Book 1 title : " << Book1.title <<endl; cout << "Book 1 author : " << Book1.author
<<endl; cout << "Book 1 subject : " << Book1.subject <<endl; cout << "Book 1 id : " <<
Book1.book_id <<endl;
// Print Book2 info
cout << "Book 2 title : " << Book2.title <<endl; cout << "Book 2 author : " << Book2.author
<<endl; cout << "Book 2 subject : " << Book2.subject <<endl; cout << "Book 2 id : " <<
Book2.book_id <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Question 1
Write a C++ program to declare a structure name book having members as book_name and
book_price, Ask user to enter record of 2 books and print the record of the book having greater price
Question 2
Add two complex numbers using structure.
Hint Output
For 1st complex number
Enter real and imaginary part respectively: 2.3 4.5
For 2nd complex number
Enter real and imaginary part respectively: 3.4 5
Sum = 5.7 + 9.5i
Question 5
Understand the following code, to gain brief knowledge about array of structures
#include<iostream> #include<string.h> using namespace std; struct stud
{
char name[50]; int marks[6];
};
4
main()
{
stud a[5];
for(int i=0;i<5;i++)
{ cout<<" student "<<i+1<<" name "<<endl;
gets(a[i].name);
}
for(int i=0;i<5;i++)
{
cout<<" student "<<i+1<<endl; for(int j=0;j<6;j++)
{
cout<<" marks for sub "<<j+1<<endl; cin>>a[i].marks[j];
}
}
cout<<"********************OUTPUT************"<<endl; for(int i=0;i<5;i++)
{
cout<<" student"<<i+1<<" name ="; cout<<a[i].name<<" "<<endl;
5
for(int c=0;c<6;c++)
{
cout<<" student "<<i+1<<" marks for sub "<<c+1; cout<<a[i].marks[c]<<" "<<endl;
}
}
}