Part 1: String conversion Write a function that takes a const c style string (ch
ID: 641734 • Letter: P
Question
Part 1: String conversion
Write a function that takes a const c style string (char *) as a parameter and returns a pointer to a c++ style string (string) containg the paramter.
The function declaration should be std::string * stringConverter(const char * str);
You must use C++ new and delete for memory allocation
Part 2: Logging input
Create a function (char * randomString()) that generates a random c style string of characters between 1 and 100 characters long.
Loop 10 times, creating random strings using your randomString() function, and convert them to c++ style strings.
Explanation / Answer
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
string *stringConverter(const char *cstr){
string *str = new string;
*str = "";
int i = 0;
while(cstr[i] != ''){
(*str) += cstr[i];
++i;
}
delete[] cstr;
return str;
}
char *randomString(){
int len = rand() % 101 + 1;
char *cstr = new char[len];
for(int i = 0; i < len; ++i){
cstr[i] = rand() % 26 + 65;
}
cstr[len - 1] = '';
return cstr;
}
int main(){
srand(time(NULL));
for(int i = 0; i < 10; ++i){
string *str = stringConverter(randomString());
cout << *(str) << endl << endl;
delete str;
}
return 0;
}