1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
// Exercise 8.4.cpp : Defines the entry point for the console application.
//
/*
Complete this skeleton by providing the described functions and prototypes. Note that there should be
two show() functions, each using default arguments, Use const arguments when appropriate. Note that set() should use new
to allocate sufficient space to hold the designated string.
*/
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <cstring>
struct stringy
{
char * str;//points to a string
int ct;//length of string (not counting '\0')
};
void set(stringy & b, const char * t);
void show(const stringy & b, int n = 1);
void show(const char *, int n = 1);
int main()
{
stringy beany;
char testing[] = "Reality isn't what it used to be.";
set(beany, testing);//first argument is a reference,
//allocates space to hold copy of testing,
//sets str member of beany to point to the new block,
//copies testing to new block,
//and sets ct member of beany
show(beany);
show(beany, 2);
testing[0] = 'D';
testing[1] = 'u';
show(testing);
show(testing, 3);
show("Done!");
system("pause");
return 0;
}
void set(stringy & b, const char * t)
{
char * pc = new char[strlen(t) + 1]; //allocates space to hold copy of testing,
b.str = pc; //sets str member of beany to point to the new block,
strcpy_s(b.str, strlen(t) + 1, t); //copies testing to new block,
b.ct = strlen(t); //and sets ct member of beany
}
void show(const stringy & b, int n)
{
for (int i = 0; i < n; i++)
cout << b.str << endl;
cout << endl;
}
void show(const char * str, int n)
{
for (int i = 0; i < n; i++)
cout << str << endl;
cout << endl;
}
|