Вы находитесь на странице: 1из 25

1.

Write a function that normally takes one argument, the address of a string, and prints
that string once. However, if a second, type int, argument is provided and is nonzero,
the function should print the string a number of times equal to the number of times that
function has been called at that point. (Note that the number of times the string is
printed is not equal to the value of the second argument; it is equal to the number of
times the function has been called.) Yes, this is a silly function, but it makes you use
some of the techniques discussed in this chapter. Use the function in a simple program
that demonstrates how the function works.
#include <iostream>

void printscr (char * mystring, int n = 0);

int main()
{
using namespace std;

char myname[] = "John Doe";

printscr(myname);
printscr(myname,5);
printscr(myname);
printscr(myname, -2);

cin.get();
cin.get();
return 0;
}

void printscr (char * mystring, int n)


{
static int called = 0;
if (n)
for (int i = 0; i < called; i++)

std::cout << mystring << std::endl;


else
std::cout << mystring << std::endl;
called++;
}

10 Responses to C++ Primer Plus Chapter 8 Exercise 1 Answer

1.

Steve says:
April 28, 2011 at 4:00 pm
My approach to this exercise was to declare a single print function, which served both
sections.
void printScr(char * str, int n = 0);
within this function is a static int which records how many times the function has
been called.
So that if a non-zero number is placed in the second argument of the function, the
string is printed the correct number of times.
Reply

admin says:
September 11, 2011 at 10:38 am
Perfect solution!
Reply

2.

Eddie says:
September 11, 2011 at 9:48 am
I tried to run this , but all I get is the name portion to show. When I input a number,
nothing happens. If I am reading this correctly, when I input a number, it should
output the same number of times as the name did. What am I misunderstanding??
Reply

admin says:
September 11, 2011 at 10:43 am
I have updated my answer for this exercise, please see the new version so you
can understand what is required.
If int number is > 0 then we should estimate how many times the printscr
function has been called at that point, and display the string as many times as
the function has been called. We dont need to display int number.
So, at the line printscr(myname,5); the printscr function has been called 2
times (not including the current line), so we need to display the string 2 times.
Reply

3.

Trance says:
December 17, 2011 at 2:48 pm
It says in the exercise if a second, type int, argument is provided and is NONZERO,
the function should print
in your function printscr() the if statement should be:
if (n)
for (int i = 0; i < called; i++)
std::cout << mystring << std::endl;
else
std::cout << mystring <0)
Just saying
Reply

admin says:
December 17, 2011 at 4:33 pm
Good catch, thx!
Also, the function counts how many times its been called prior the current
call that displays the string.
Reply

4.

Wei says:
December 22, 2011 at 9:05 am
Just one question
You used static int in the definition of the function,
however the question said use some of the techniques discussed in this chapter,
so Im wondering if theres any relevant technique (other than static variable) that can
make it?
Thanks!
Reply

5.

DOOM says:
March 21, 2012 at 12:33 pm
Well m new to c++ and words like static petrify me for now. I think if we use a
global variable we have a much simpler solution.
#include
using std::namespace;
int calls = 1;
void print(const char *s, int n = 0);
int main()
{
char s[50] = HAHA;
print(s);
print(s, 3);
print(s, -2);
print(s);
print(s, 2);
return 0;
}
void print (const char *s, int n)
{
cout << "In the function with " << ::calls << " calls yet " < 0)
{
for(int i = 0; i < calls; i++)

cout << s << endl;


}
else
cout << s << endl;
++(::calls);
}
Reply

6.

Yechiel Labunskiy says:


July 7, 2012 at 8:39 pm
Yeah I think the book wanted us to use a global variable.
How does static work here? How come each time the function is called the static
variable isnt reassigned the value 0? Does static mean that the assignment takes
only once and thats it?
Thanks.
Reply

7.

says:
September 27, 2012 at 11:36 am
I think for (int i = 0; i < called; i++)" should be changed to "for (int i = 0; i < =
called; i++)",which is the real meaning of the exercise.
And this is my answer:
#include
#include
using namespace std;
void display(string str ,int n = 0);
int main()
{
string input;
cout<<"Enter something:\n";
getline(cin,input);
cout<<"Result:\n";
display(input);
cout<<endl;
display(input,3);
cout<<endl;
display(input,-7);

cout<<endl;
display(input,0);
cout<<endl;
display(input,110);
cin.get();
cin.get();
return 0;
}
void display(string str ,int n)
{
static int count = 0;
if(n)
for(int i=0;i<=count;i++)
cout<<str<<endl;
else
cout<<str<<endl;
count++;
}
2. The CandyBar structure contains three members. The first member holds the brand
name of a candy bar. The second member holds the weight (which may have a fractional
part) of the candy bar, and the third member holds the number of calories (an integer
value) in the candy bar. Write a program that uses a function that takes as arguments a
reference to CandyBar, a pointer-to-char, a double, and an int and uses the last three
values to set the corresponding members of the structure. The last three arguments
should have default values of Millennium Munch, 2.85, and 350. Also, the program
should use a function that takes a reference to a CandyBar as an argument and displays
the contents of the structure. Use const where appropriate.
1

#include <iostream>

2
3
4

struct CandyBar
{
char * brand;

double weight;

int calories;

7
8

};

9
void setcandy (CandyBar & st, char * brandname = "Millennium Munch", double stweight = 2.85,
10
int cal = 350);
11
void dispcandy (CandyBar const & st);

12
13
14int main()
15{
16using namespace std;
17
18CandyBar snickers;
19
20setcandy(snickers); // setting snickers to default values
21cout << "Displaying structure with default values.\n";
22dispcandy(snickers);
23
24cout << "\n\nDisplaying structure with modified values.\n";
25setcandy(snickers,"Snickers",1.1,400); // setting custom values
26dispcandy(snickers);
27
28cin.get();
29cin.get();
30return 0;
31}
32
33void setcandy (CandyBar & st, char * brandname, double stweight, int cal)
34{
35 st.brand = brandname;
36 st.weight = stweight;
37 st.calories = cal;
38}
39
40void dispcandy (CandyBar const & st)
41{
42 using namespace std;

43
44 cout << "\nBrand Name: " << st.brand;
45 cout << "\nWeight: " << st.weight;
46 cout << "\nCalories: " << st.calories;
47}

One Response to C++ Primer Plus Chapter 8 Exercise 2 Answer

1.

says:
September 27, 2012 at 12:16 pm
My solution:
#include
struct CandyBar
{
char* brand;
float weight;
int heat;
};
void set(CandyBar & str,char* b = Millennium Munch,const float w = 2.85,const
int h = 350);
void display(const CandyBar & str);
int main()
{
using namespace std;
CandyBar goods;
set(goods);
display(goods);
cin.get();
return 0;
}
void set(CandyBar & str,char* b,const float w,const int h)
{
str.brand = b;
str.weight = w;

str.heat = h;
}
void display(const CandyBar & str)
{
using namespace std;
cout<<"Brand: "
<<str.brand
<<endl;
cout<<"Weight: "
<<str.weight
<<endl;
cout<<"Quantity of heat: "
<<str.heat
<<endl;
}
3. Write a function that takes a reference to a string object as its parameter and that converts
the contents of the string to uppercase. Use the toupper() function described in
Table 6.4. Write a program that uses a loop which allows you to test the function with
different input. A sample run might look like this:
Enter a string (q to quit): go away
GO AWAY
Next string (q to quit): good grief!
GOOD GRIEF!
Next string (q to quit): q
Bye.
1 #include <iostream>
2 #include <cctype>
3 #include <string>
4
5 using namespace std;
6
7 void convupper (string & phrase);
8
9 int main()
10{
11
12string myphrase;;

13
14do
15{
16 cout << "Enter a string (q to quit): ";
17 getline(cin,myphrase);
18 if (myphrase == "q")
19

break;

20 convupper(myphrase);
21 cout << endl << myphrase << endl;
22}
23while (myphrase != "q");
24
25
26cout << "\nBye!!";
27cin.get();
28cin.get();
29return 0;
30}
31
32void convupper (string & phrase)
33{
34 for (int i = 0; i < phrase.size(); i++)
35

phrase[i]=toupper(phrase[i]);

36}
37

3 Responses to C++ Primer Plus Chapter 8 Exercise 3 Answer

1.

Saad says:
February 19, 2012 at 6:10 pm

// C++ Primer Plus Exercise


// Chapter 8, Exercise 3
#include
#include
#include
//- Function Prototype(s)
void caps(std::string &);
//
int main()
{
using namespace std;
string input;
cout << "Enter string (q to quit): ";
while(getline(cin, input) && input != "q" && input != "Q")
{
caps(input);
cout << input;
cout << "\nEnter string (q to quit): ";
}
cout << "Adios!";
return 0;
}
void caps(std::string &input)
{
for(int i=0; i<input.size(); i++)
{
input[i]=std::toupper(input[i]);
}
}
Reply

2.

says:
September 27, 2012 at 1:24 pm
My solution:
#include
#include
#include

using namespace std;


string & convert(string & onestr);
int main()
{
string input;
cout<<"Enter a string (q to quit): ";
getline(cin,input);
while(input!="q")
{
cout<<convert(input)<<endl;
cout<<"Next string (q to quit): ";
getline(cin,input);
}
cout<<"Bye."<<endl;
cin.get();
return 0;
}
string & convert(string & onestr)
{
for(int i = 0;i<onestr.size();i++)
onestr[i]=toupper(onestr[i]);
return onestr;
}
Reply

3.

Daniel says:
March 29, 2013 at 5:12 pm
void upp(string &phrase)
{
for (string::iterator it=phrase.begin();it!=phrase.end();++it)
*it=toupper(*it);
}

4. The following is a program skeleton:


#include iostream
using namespace std;
#include // for strlen(), strcpy()
struct stringy {
char * str; // points to a string

int ct; // length of string (not counting \0)


};
// prototypes for set(), show(), and show() go here
int main()
{
stringy beany;
char testing*+ = Reality isnt 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); // prints member string once
show(beany, 2); // prints member string twice
testing*0+ = D;
testing*1+ = u;
show(testing); // prints testing string once
show(testing, 3); // prints testing string thrice
show(Done!);
return 0;
}
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. The techniques used here are similar to those used in designing
and implementing classes. (You might have to alter the header filenames and delete
the using directive, depending on your compiler.)
1 #include <iostream>
2 #include <cstring> // for strlen(), strcpy()
3
4 using namespace std;
5
6 struct stringy {
7 char * str; // points to a string
8 int ct; // length of string (not counting \0)
9 };
10
11// prototypes for set(), show(), and show() go here
12void set (stringy & st, char * charstring);

13inline void show (stringy const & dispst) {cout << dispst.str << endl;}
14inline void show (char const * charst) {cout << charst << endl;}
15void show (stringy const & st, int n);
16void show (char const * charst, int n);
17
18int main()
19{
20
21stringy beany;
22char testing[] = "Reality isn't what it used to be.";
23set(beany, testing); // first argument is a reference,
24// allocates space to hold copy of testing,
25// sets str member of beany to point to the
26// new block, copies testing to new block,
27// and sets ct member of beany
28show(beany); // prints member string once
29show(beany, 2); // prints member string twice
30testing[0] = 'D';
31testing[1] = 'u';
32show(testing); // prints testing string once
33show(testing, 3); // prints testing string thrice
34show("Done!");
35
36cin.get();
37cin.get();
38delete [] beany.str;
39return 0;
40}
41
42void set (stringy & st, char * charstring)
43{

44 st.ct = strlen(charstring);
45 st.str = new char [st.ct+1]; // +1 for '\0' end of string char
46 strcpy(st.str,charstring);
47}
48
49void show (stringy const & st, int n)
50{
51 for (int i=0; i < n; i++)
52

cout << st.str << endl;

53}
54
55void show (char const * charst, int n)
56{
57 for (int i=0; i < n; i++)
58

cout << charst << endl;

59}

3 Responses to C++ Primer Plus Chapter 8 Exercise 4 Answer

1.

Zhang says:
October 7, 2012 at 12:03 pm
My answer:
#include
using namespace std;
#include
struct stringy
{
char* str;
int ct;
};
void set(stringy & ft,const char*ps);
void show(const stringy & ft,const int n=1);
void show(const char* ps,const int m=1);

int main()
{
stringy beany;
char testing[]=Reality isnt what it used to be.;
set(beany,testing);
show(beany);
show(beany,2);
testing[0]=D';
testing[1]=u';
show(testing);
show(testing,3);
show(Done!);
return 0;
}
void set(stringy & ft,const char* ps)
{
ft.ct=strlen(ps);
ft.str=new char[ft.ct];
strcpy(ft.str,ps);
}
void show(const stringy & ft,const int n)
{
for(int i=0;i<n;i++)
cout<<ft.str<<endl;
cout<<endl;
}
void show(const char* ps,const int m)
{
for(int i=0;i<m;i++)
cout<<ps<<endl;
cout<<endl;
}
Reply

2.

richard says:
December 16, 2012 at 10:48 pm
why does inline work in your code?? why is it needed?
Reply

3.

richard says:
December 16, 2012 at 11:07 pm
A little different than yours but your inline functions are not necessary.
using namespace std;
struct stringy
{
char * str; // points to a string
int ct; // length of string (not counting )
};
// prototypes for set(), show(), and show() go here
void set(stringy &strin, char *ptr);
void show(stringy const &bean, int num = 0);
void show(char const *charst, int num = 0);
int main()
{
stringy beany;
char testing[] = Reality isnt 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
cout << "once" << endl;
show(beany); // prints member string once
cout << "twice" << endl;
show(beany, 2); // prints member string twice
cout << "all done" << endl;
testing[0] = 'D';
testing[1] = 'u';
show(testing); // prints testing string once
show(testing, 3); // prints testing string thrice
show("Done!");
return 0;
}
void set(stringy &strin, char *ptr)
{
strin.str = new char[];
strcpy(strin.str, ptr);

strin.ct = strlen(ptr);
}
void show(stringy const &bean, int num)
{
if (num)
for (int i = 0; i < num; ++i)
cout << bean.str << endl;
else
cout << bean.str << endl;
}
void show(char const *charst, int num)
{
if (num)
for (int i = 0; i < num; ++i)
cout << charst << endl;
else
cout << charst << endl;
}

5. Write a template function max5() that takes as its argument an array of five items of type
T and returns the largest item in the array. (Because the size is fixed, it can be hard-coded
into the loop instead of being passed as an argument.) Test it in a program that uses the
function with an array of five int value and an array of five double values.
1 #include <iostream>
2
3 template <typename T>
4 T Max5 (T arr[]);
5
6 int main()
7 {
8 using namespace std;
9
10int arr[5] = {11,2,33,24,5};
11double arr2[5] = {22.5,33.6,33.63,5.7,11.5};
12
13cout << "The max of INTs is " << Max5(arr);
14cout << "\nThe max of DOUBLEs is " << Max5(arr2);

15
16cin.get();
17cin.get();
18return 0;
19}
20
21template <typename T>
22T Max5 (T arr[])
23{
24 T max = arr[0];
25
26 for (int i=1; i<5; i++)
27

if (max < arr[i])

28

max = arr[i];

29
30 return max;
31}

6. Write a template function maxn() that takes as its arguments an array of items of type T
and an integer representing the number of elements in the array and that returns the
largest item in the array. Test it in a program that uses the function template with an
array of six int value and an array of four double values. The program should also
include a specialization that takes an array of pointers-to-char as an argument and the
number of pointers as a second argument and that returns the address of the longest
string. If multiple strings are tied for having the longest length, the function should
return the address of the first one tied for longest. Test the specialization with an array of
five string pointers.
1 #include <iostream>
2
3 template <typename T>
4 T maxn (T arr[], int n);
5
6 template <> char * maxn <char *>(char * pt[], int n);

7
8 int main()
9 {
10using namespace std;
11
12char * pt [5] = {"Arnold Schwarznegger",
13

"Joe Pesci",

14

"Silvester Stallone",

15

"Robert DeNiro",

16

"Charlie Chaplin"};

17
18char * pt2 = maxn(pt,5);
19int arr[6] = {11,2,33,24,85,6};
20double arr2[4] = {22.5,5.7,11.5,17.0};
21
22
23cout << "The max of INTs is " << maxn(arr,6) << endl;
24cout << "The max of DOUBLEs is " << maxn(arr2,4) << endl;
25cout << "The longest length string - " << pt2;
26
27cin.get();
28cin.get();
29return 0;
30}
31
32template <typename T>
33T maxn (T arr[], int n)
34{
35 T max = arr[0];
36
37 for (int i=1; i<n; i++)

38

if (max < arr[i])

39

max = arr[i];

40
41 return max;
42}
43
44template <> char * maxn <char *>(char * pt[], int n)
45{
46 int max;
47 int maxindex;
48
49 max = strlen(pt[0]);
50 maxindex = 0;
51
52
53 for (int i=0; i < n; i++)
54 {
55

if (max < strlen(pt[i]))

56

57

max = strlen(pt[i]);

58

maxindex = i;

59

60 }
61 return pt[maxindex];
62}

5 Responses to C++ Primer Plus Chapter 8 Exercise 6 Answer

1.

V says:
June 2, 2011 at 9:19 pm
Thanks!

Reply

2.

richard says:
December 16, 2012 at 11:42 pm
you dont need in your template
Reply

3.

richard says:
December 16, 2012 at 11:42 pm
Reply

4.

Schaft says:
April 3, 2013 at 2:58 am
Hi . Thanks for the code.
BTW , #include is necessary for strlen().
And a question :
if you have defined the template like this :
template T maxn (const T arr[], int n);
any idea how the explicit specialization protoype would look like ?
Reply

5.

l0ner says:
August 12, 2013 at 6:47 pm
Better specialization:
template <> char * maxn<char *>(char * arr[], unsigned len) {
char * max = arr[0];
for(unsigned i = 0; i < len; i++)
if(strlen(arr[i]) > strlen(max))
max = arr[i];

return max;
}

7. Modify Listing 8.14 so that the template functions return the sum of the array contents
instead of displaying the contents. The program now should report the total number of
things and the sum of all the debts.
1 // tempover.cpp --- template overloading
2 #include <iostream>
3
4 template <typename T> // template A
5 T ShowArray(T arr[], int n);
6
7 template <typename T> // template B
8 double ShowArray(T * arr[], int n);
9
10struct debts
11{
12char name[50];
13double amount;
14};
15
16int main(void)
17{
18
19 using namespace std;
20 int things[6] = {13, 31, 103, 301, 310, 130};
21 struct debts mr_E[3] =
22 {
23 {"Ima Wolfe", 2400.0},
24 {"Ura Foxe", 1300.0},
25 {"Iby Stout", 1800.0}

26 };
27
28 double * pd[3];
29
30 // set pointers to the amount members of the structures in the arr mr_E
31 for (int i = 0; i < 3; i++)
32

pd[i] = &mr_E[i].amount;

33
34 cout << "The sum of Mr. Es things: " << ShowArray(things, 6) << endl;
35 cout << "The sum of Mr. Es debts: " << ShowArray(pd, 3) << endl;
36
37cin.get();
38cin.get();
39return 0;
40}
41
42template <typename T>
43T ShowArray(T arr[], int n)
44{
45 T sum = 0;
46 using namespace std;
47 cout << "template A\n";
48 for (int i = 0; i < n; i++)
49

sum += arr[i];

50 return sum;
51}
52
53template <typename T>
54double ShowArray(T * arr[], int n)
55{
56 double sum = 0;

57 using namespace std;


58 cout << "template B\n";
59 for (int i = 0; i < n; i++)
60

sum += *arr[i];

61 return sum;
62}

2 Responses to C++ Primer Plus Chapter 8 Exercise 7 Answer

1.

masooma abham says:


January 17, 2012 at 11:29 pm
good very good and help full,
Reply

2.

richard says:
December 16, 2012 at 11:55 pm
template
double ShowArray(T * arr[], int n)
that template can have return type t and doesnt have to have double

Вам также может понравиться