c++ 5. getString Function Write a function named getString that has a local char
ID: 3631996 • Letter: C
Question
c++ 5. getString FunctionWrite a function named getString that has a local char array of 80 elements.
The function should ask the user to enter a sentence, and store the sentence
in the array. Then the function should dynamically allocate a char array
just large enough to hold the sentence, plus the null terminator. It should
copy the sentence to the dynamically allocated array, and then return a
pointer to the array. Demonstrate the function in a complete program.
Note: You need to write your own string copy function, not use the standard library version.
its for starting out with c++ 6ed tony g.
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
//PROTOTYPES
char* getString();
//LOCAL DECLARATIONS
//PROCEDURES
cout << "Enter sentence 1: ";
char* sentence1 = getString();
cout << " Sentence 1: " << sentence1 << endl;
cout << " Enter sentence 2: ";
char* sentence2 = getString();
cout << " Sentence 1: " << sentence2 << endl;
//Because getString() use dynamic allocation or the new keyword, you'll have to delete those dynamic array
delete [] sentence1;
delete [] sentence2;
cin.get();
return 0;
}
//---------------------------------------------------------
// FUNCTION DEFINITIONS
//---------------------------------------------------------
char* getString()
{
const int BUF_SIZE = 80;
char buf[BUF_SIZE];
int bufCharCount = 0;
int i;
cin.getline(buf, BUF_SIZE); //get input line
for (i = 0; buf[i] != 0; ++i) //count the characters in the line
{
bufCharCount++;
}
char *dynamicString = new char[bufCharCount + 1]; //dynamic allocate the appropriate memory for these characters
for (i = 0; buf[i] != 0; ++i) //copy from the buffer string to the dynamic string
{
dynamicString[i] = buf[i];
}
dynamicString[bufCharCount] = ''; //the end char of dynamic string must be null
return dynamicString;
}
************Sample output*************
Enter sentence 1: This is first line
Sentence 1: This is first line
Enter sentence 2: And this is second line . .
Sentence 1: And this is second line . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.