LAB 2 – Char Arrays and Strings (INDIVIDUAL
WORK)
In-lab activity (due at the end of the lab
session)
Examine the
following function prototype:
int strcmp(const char string1[],
const char string2[]);
The previous
function is used to manipulate data stored in char arrays, as you will see in
the following example. Copy and paste the code into a blank .cpp file, like you did in the first lab session. Print the
output of the program and carefully examine the code within each function as
you read through the printout. Your job is to figure out how the samples work.
Print the source
code and write next to each sentence (excepting for those that output something
to the screen) a brief comment/explanation of what is being accomplished.
Answer the question in sample3.
Turn in both
printouts. Don’t forget to type/print your name on every page you turn in.
Homework (due next lab session)
Investigate the
prototype of strcpy. Write it down and provide a
brief explanation.
Investigate the
prototypes of the functions (methods) used in sample3. Write them down and
provide a brief explanation.
Write a function int find(char
source[],
char target[]) that would find target
within source.
#include <cstring>
#include <iostream>
using namespace
std;
const char word[] = "We shall go on to the end... We shall
never surrender";
const char fmt1[] = " 1 2 3 4 5
";
const char fmt2[] =
"12345678901234567890123456789012345678901234567890123";
const char word1[] = "Be quick or
be dead";
const char word2[] = "Be QUICK or
be dead";
void sample1(){
char
w[80];
strcpy(w, "Initializing ");
strcat(w, "and ");
strcat(w, "concatenating ");
cout
<< "Result :" << w << endl;
}
void sample2(){
char
tmp[20];
int result;
// Case sensitive
cout
<< "Comparing " << word1 << " and "
<< word2 << endl;
result = strcmp(word1, word2);
if(result
> 0)
strcpy(tmp, "greater than ");
else
if( result < 0 )
strcpy(tmp, "less than ");
else
strcpy(tmp, "equal to ");
cout
<< word1 << " is " << tmp
<< " than " << word2;
// Case
insensitive
cout
<< endl;
result = strcasecmp(word1, word2);
if(result
> 0)
strcpy(tmp, "greater than ");
else
if( result < 0 )
strcpy(tmp, "less than ");
else
strcpy(tmp, "equal to ");
cout
<< word1 << " is " << tmp
<< word2;
cout
<< endl;
}
void sample3(){
string s =
"This is a string, NOT a char array";
cout
<< s.length() << endl;
cout
<< s.size() << endl;
cout
<< s.find("NOT") << endl;
cout
<< s.find('i')
<< endl;
cout
<< s.find("not") << endl;
cout << s + ", see? " << endl;
cout
<< static_cast <string> ("my ")
+ " God! " << endl;
cout
<< (string) "my " + " God!" << endl;
// cout
<< "my " + " God!" << endl; <--- would this compile? why or why not?
cout
<< s.compare("This is a string")
<< endl;
cout
<< s.compare("This is a string, NOT a char
array") << endl;
}
void main(){
sample1();
sample2();
sample3();
}