0% found this document useful (0 votes)
9 views12 pages

Lab Manual 09-12

This lab manual covers the use of Strings in C++ programming, explaining the differences between C strings and the string class. It includes examples of string manipulation functions like strcpy and strlen, as well as an introduction to pointers and structures in C++. The document provides code examples and exercises to enhance understanding of these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views12 pages

Lab Manual 09-12

This lab manual covers the use of Strings in C++ programming, explaining the differences between C strings and the string class. It includes examples of string manipulation functions like strcpy and strlen, as well as an introduction to pointers and structures in C++. The document provides code examples and exercises to enhance understanding of these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1

LAB MANUAL 9-12

STRINGS

Lab Objectives:

At the end of this lab students will know about

 What is the purpose of Strings?


 How to use Strings in C++ programs
Strings

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.

To declare a character array:

char s1[8];

To assign a value to an array when you declare it:

char s1[8] = "one";

Actually, if you are assigning a value at the same time as


you are declaring the char array, you don't
need to specify an array size.

char s1[] = "one";

Assigning a value either way results in a character


array of finite length, established at compile time.

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

To assign a value after the declaration, you need to use


a C String function such as strcpy. We'll look at that next.
2

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!";

cout << "Before strcpy(): " << endl;


cout << "Original = " << Original << endl;
cout << "Copy = " << Copy << endl;

strcpy(Copy, Original);
cout << "After strcpy(): " << endl;
cout << "Original = " << Original << endl;
cout << "Copy = " << Copy << endl;

return 0;

Here is the running result of the above program:

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!";

cout << "Here is string:" << String << endl;


cout << "Its length is: " << strlen(String) << " characters\n";

return 0;

Here is the running result of the above program:

Here is string:I am the string!


Its length is: 16 characters

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:

char s1[80], s2[80], s3[80];

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.

// Purpose: Demonstrates the use of the string class


#include <iostream>
#include <string>
using namespace std;

int main()
{
string str1("This is a test");
string str2("ABCDEFG");

cout << "Initial strings: \n";


cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << "\n\n";

// demonstrate length()
cout << "Length of str1 is: " << str1.length() << endl;

return 0;
}

Here is how it runs:

Initial strings:
str1: This is a test
str2: ABCDEFG

Length of str1 is: 14


1

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;
}

WHAT ARE POINTERS?

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 −

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

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.

USING POINTERS IN C++

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 makes use of these operations −


3

Example
#include <iostream>

using namespace std;

int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as follows −

Value of var variable: 20


Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Question 1

What will be the output of the following program?

#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 −

struct [structure tag] { member definition; member definition;


...
member definition;
} [one or more structure variables];

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

ACCESSING STRUCTURE MEMBERS


To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that we
wish to access. You would use struct keyword to define variables of structure type. Following is the
example to explain usage of structure −

#include <iostream> #include <cstring>


using namespace std; struct Books {
char title[50];
char author[50]; char subject[100]; int book_id;
};

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 −

Book 1 title : Learn C++ Programming


3

Book 1 author : Chand Miyan


Book 1 subject : C++ Programming Book 1 id : 6495407
Book 2 title : Telecom Billing Book 2 author : Yakit Singha Book 2 subject : Telecom
Book 2 id : 6495700

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;
}
}
}

You might also like