C++ Lab you will implement YOUR OWN VERSIONS of some functions available for ‘cs
ID: 673393 • Letter: C
Question
C++ Lab
you will implement YOUR OWN VERSIONS of some functions available for ‘cstring’. in C++
The functions to be implemented/duplicated are:
i. strlen (original) --> stringLength (yours)
ii. strncpy (original) --> stringNCopy (yours)
iii. strcat (original) --> stringAdd (yours)
iv strcmp (original) --> stringCompare (yours)
REMEMBER -
The objective of this assignment is for you to duplicate the functionality provided by the original functions.
DO NOT USE the original functions to provide the functionality of your functions, otherwise you will lose major points.
Refer to http://www.cplusplus.com to get function prototypes of the original. You may match them exactly or change them if you like.
You have to use pointers and not array/subscript behaviors. Use of arrays inside the functions will result in large deductions.
Bounds checking is not required but you may choose to implement it.
Your main function should provide the user a menu of options on which function to test and then ask for the appropriate input to test the function and provide the output. One of the menu options should be to continue the test or exit the program.
Explanation / Answer
#include <iostream>
using namespace std;
int stringLength(char *str) {
int i=0;
while(str[i] != '')
i++;
return i;
}
char *stringNCopy(char *dest, const char *src, size_t n)
{
size_t i;
for (i = 0; i < n && src[i] != ''; i++)
dest[i] = src[i];
for ( ; i < n; i++)
dest[i] = '';
return dest;
}
char *stringAdd(char *dest, const char *src)
{
size_t dest_len = stringLength(dest);
int i;
for (i = 0 ; src[i] != '' ; i++)
dest[dest_len + i] = src[i];
dest[dest_len + i] = '';
return dest;
}
int stringCompare (const char *s1, const char *s2) {
const unsigned char *p1 = (const unsigned char *)s1;
const unsigned char *p2 = (const unsigned char *)s2;
while (*p1 != '') {
if (*p2 == '') return 1;
if (*p2 > *p1) return -1;
if (*p1 > *p2) return 1;
p1++;
p2++;
}
if (*p2 != '') return -1;
return 0;
}
int main() {
char str[] = "very good ";
char str1[40] = "einstein ";
char str2[40];
stringNCopy(str2, str, sizeof(str));
stringAdd(str1, str);
cout<<"Length of string is: "<<stringLength(str)<<" ";
cout<<"New copied string: "<<str2<<" ";
cout<<"Concat string: "<<str1<<" ";
cout<<"Compare strings: "<<stringCompare(str1, str)<<" ";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.