书内代码部分
程序清单 4.1
// arrayone.cpp -- small arrays of integers
#include <iostream>
int main()
{
using namespace std;
int yams[3] = { 0 }; // Creates array with three elements
yams[0] = 7; // Assign value to first element
yams[1] = 8;
yams[2] = 6;
// NOTE: If your C++ compiler or translator can't initialize this array, use static int yamcosts[3]
// instead of int yamcosts[3]
int yamcosts[3] = { 20, 30, 5 }; // Create, initialize array
cout << "Total yams = ";
cout << yams[0] + yams[1] + yams[2] << endl;
cout << "The package with " << yams[1] << " yams costs ";
cout << yamcosts[1] << " cents per yam.\n";
int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1];
total = total + yams[2] * yamcosts[2];
cout << "The total yam expense is " << total << " cents.\n";
cout << "\nSize of yams array = " << sizeof yams;
cout << " bytes.\n";
cout << "Size of one element = " << sizeof yams[0];
cout << " bytes.\n";
return 0;
}
输出结果:
程序清单 4.2
// strings.cpp -- storing strings in an array
#include <iostream>
#include <cstring> // For the strlen function
int main()
{
using namespace std;
const int Size = 15;
char name1[Size]; // Empty array, uninitialized
char name2[Size] = "C++owboy"; // Initialized array
// Note: some implementations may require the static keyword to initialize the array name2
cout << "Howdy! I'm " << name2;
cout << "! What's your name?\n";
cin >> name1;
cout << "Well, " << name1 << ", your name has ";
cout << strlen(name1) << " letters and is stored\n";
cout << "in an array of " << sizeof(name1) << " bytes.\n";
cout << "Your initial is " << name1[0] << ".\n";
name2[3] = '\0'; // Set to null character
cout << "Here are the first 3 characters of my name: ";
cout << name2 << endl;
return 0;
}
输出结果:
程序清单 4.3
// instr1.cpp -- reading more than one string
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin >> name;
cout << "Enter your favorite dessert:\n";
cin >> dessert;
cout << "I have some dilicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}
输出结果:
程序清单 4.4
// instr2.cpp -- reading more than one word with getline
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.getline(name, ArSize); // Reads through newline
cout << "Enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}
输出结果:
程序清单 4.5
// instr3.cpp -- reading more than one word with get() & get()
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.get(name, ArSize).get(); // Reading string, newline
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize).get();
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
return 0;
}
输出结果:
程序清单 4.6
// numstr.cpp -- following number input with line input
#include <iostream>
int main()
{
using namespace std;
cout << "What year was your house built?\n";
int year;
(cin >> year).get(); // Or (cin >> year).get(ch); or add cin.get(); or add cin.get(ch);
cout << "What is its street address?\n";
char address[80];
cin.getline(address, 80);
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
return 0;
}
输出结果:
程序清单 4.7
// strType.cpp -- using the C++ string class
#include <iostream>
#include <string> // Make string class available
int main()
{
using namespace std;
char charr1[20]; // Create an empty array
char charr2[20] = "jaguar"; // Create an initialized array
string str1; // Create an empty string object
string str2 = "panther"; // Create an initialized string
cout << "Enter a kind of feline: ";
cin >> charr1;
cout << "Enter another kind of feline: ";
cin >> str1; // Use cin for input
cout << "Here are some felines:\n"; // Use cout for output
cout << charr1 << " " << charr2 << " " << str1 << " " << str2 << endl;
cout << "The third letter in " << charr2 << " is " << charr2[2] << endl;
cout << "The third letter in " << str2 << " is " << str2[2] << endl; // Using array notation
return 0;
}
输出结果:
程序清单 4.8
// strType2.cpp -- assigning, adding, and appending
#include <iostream>
#include <string> // Make string class available
int main()
{
using namespace std;
string s1 = "penguin";
string s2, s3;
cout << "You can assign one string object to another: s2 = s1\n";
s2 = s1;
cout << "s1: " << s1 << ", s2: " << s2 << endl;
cout << "You can assign a C-style string to a string object.\n";
cout << "s2 = \"buzzard\"\n";
s2 = "buzzard";
cout << "s2: " << s2 << endl;
cout << "You can concatenate strings: s3 = s1 + s2\n";
s3 = s1 + s2;
cout << "s3: " << s3 << endl;
cout << "You can append strings.\n";
s1 += s2;
cout << "s1 += s2 yields s1 = " << s1 << endl;
s2 += " for a day";
cout << "s2 += \" for a day\" yields s2 = " << s2 << endl;
return 0;
}
输出结果:
程序清单 4.9
// strType3.cpp -- more string class features
#include <iostream>
#include <string> // Make string class available
#include <cstring> // C-style string library
int main()
{
using namespace std;
char charr1[20];
char charr2[20] = "jaguar";
string str1;
string str2 = "panther";
// Assignment for string objects and character arrays
str1 = str2; // Copy str2 to str1
strcpy_s(charr1, charr2); // Copy charr2 to charr1
// Appending for string objects and character arrays
str1 += " paste"; // Add paste to end of str1
strcat_s(charr1, " juice"); // And juice to end of charr1
// Finding the length of a string object and a C-style string
int len1 = str1.size(); // Obtain length of str1
int len2 = strlen(charr1); // Obtain length of charr1
cout << "The string " << str1 << " contains " << len1 << " characters.\n";
cout << "The string " << charr1 << " contains " << len2 << " characters.\n";
return 0;
}
输出结果:
程序清单 4.10
// strType4.cpp -- line input
#include <iostream>
#include <string> // Make string class available
#include <cstring> // C-style string library
int main()
{
using namespace std;
char charr[20];
string str;
cout << "Length of string in charr before input: " << strlen(charr) << endl;
cout << "Length of string in str before input: " << str.size() << endl;
cout << "Enter a line of text:\n";
cin.getline(charr, 20); // Indicate maximum length
cout << "You entered: " << charr << endl;
cout << "Enter another line of text:\n";
getline(cin, str); // cin now an argument; no length specifier
cout << "You entered: " << str << endl;
cout << "Length of string in charr after input: " << strlen(charr) << endl;
cout << "Length of string in str after input: " << str.size() << endl;
return 0;
}
输出结果:
程序清单 4.11
// structur.cpp -- a simple structure
#include <iostream>
struct Inflatable { // Structure declaration
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
Inflatable guest = {
"Glorious Gloria", // name value
1.88, // volume value
29.99 // price value
}; // guest is a structure variable of type inflatable
// It's initialized to the indicated values
Inflatable pal = {
"Audacious Arthur",
3.12,
32.99
}; // pal is a good second variable of type inflatable
// NOTE: some implementations require using static inflatable guest
cout << "Expand your guest list with " << guest.name;
cout << " and " << pal.name << "!\n"; // pal.name is the name member of the pal variable
cout << "You can have both for $";
cout << guest.price + pal.price << "!\n";
return 0;
}
输出结果:
程序清单 4.12
// assgn_st.cpp -- assigning structures
#include <iostream>
struct Inflatable {
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
Inflatable bouquet = { "sunflowers", 0.20, 12.49 };
Inflatable choice;
cout << "bouquet: " << bouquet.name << " for $" << bouquet.price << endl;
choice = bouquet; // Assign one structure to another
cout << "choice: " << choice.name << " for $" << choice.price << endl;
return 0;
}
输出结果:
程序清单 4.13
// arrstruc.cpp -- an array of structures
#include <iostream>
struct Inflatable {
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
Inflatable guests[2] = { // Initializing an array of structs
{ "Bambi", 0.5, 21.99 }, // First structure in array
{ "Godzilla", 2000, 565.99 } // Next structure in array
};
cout << "The guests " << guests[0].name << " and " << guests[1].name
<< "\nhave a combined volume of " << guests[0].volume + guests[1].volume
<< " cubic feet.\n";
return 0;
}
输出结果 :
程序清单 4.14
// address.cpp -- using the & operator to find addresses
#include <iostream>
int main()
{
using namespace std;
int donuts = 6;
cout << "donuts value = " << donuts;
cout << " and donuts address = " << &donuts << endl;
// NOTE: you may need to use unsigned (&donuts) and unsigned (&cups)
double cups = 4.5;
cout << "cups value = " << cups;
cout << " and cups address = " << &cups << endl;
return 0;
}
输出结果:
程序清单 4.15
// pointer.cpp -- our first pointer variable
#include <iostream>
int main()
{
using namespace std;
int updates = 6; // Declare a variable
int *p_updates; // Declare pointer to an int
p_updates = &updates; // Assign address of int to pointer
// Express values two ways
cout << "Values: updates = " << updates;
cout << ", *p_updates = " << *p_updates << endl;
// Express address two ways
cout << "Addresses: &updates = " << &updates;
cout << ", p_updates = " << p_updates << endl;
// Use pointer to change value
*p_updates = *p_updates + 1;
cout << "Now updates = " << updates << endl;
return 0;
}
输出结果:
程序清单 4.16
// init_ptr.cpp -- initialize a pointer
#include <iostream>
int main()
{
using namespace std;
int higgens = 5;
int *pt = &higgens;
cout << "Value of higgens = " << higgens << "; Address of higgens = " << &higgens << endl;
cout << "Value of *pt = " << *pt << "; Vaule of pt = " << pt << endl;
return 0;
}
输出结果:
程序清单 4.17
// use_new.cpp -- using the new operator
#include <iostream>
int main()
{
using namespace std;
int nights = 1001;
int *pt = new int; // Allocate space for an int
*pt = 1001; // Store a value there
cout << "nights value = ";
cout << nights << ": location " << &nights << endl;
cout << "int ";
cout << "Value = " << *pt << ": location = " << pt << endl;
double *pd = new double; // Allocate space for a double
*pd = 10000001.0; // Store a double there
cout << "double ";
cout << "value = " << *pd << ": location = " << pd << endl;
cout << "location of pointer pd: " << &pd << endl;
cout << "size of pt = " << sizeof(pt);
cout << ": size of *pt = " << sizeof(*pt) << endl;
cout << "size of pd = " << sizeof pd;
cout << ": size of *pt = " << sizeof(*pd) << endl;
return 0;
}
输出结果:
程序清单 4.18
// arraynew.cpp -- using the new operator for arrays
#include <iostream>
int main()
{
using namespace std;
double *p3 = new double[3]; // Space for 3 doubles
p3[0] = 0.2; // Treat p3 like an array name
p3[1] = 0.5;
p3[2] = 0.8;
cout << "p3[1] is " << p3[1] << ".\n";
p3 += 1; // Increment the pointer
cout << "Now p3[0] is " << p3[0] << " and ";
cout << "p3[1] is " << p3[1] << ".\n";
p3 -= 1; // Point back to beginning
delete[] p3; // Free the memory
return 0;
}
输出结果:
程序清单 4.19
// addpntrs.cpp -- pointer addition
#include <iostream>
int main()
{
using namespace std;
double wages[3] = { 10000.0, 20000.0, 30000.0 };
short stacks[3] = { 3, 2, 1 };
// Here are two ways to get the address of an array
double *pw = wages; // Name of an array = address
short *ps = &stacks[0]; // Or use address operator with array element
cout << "pw = " << pw << ", *pw = " << *pw << endl;
pw = pw + 1;
cout << "add 1 to the pw pointer:\n";
cout << "pw = " << pw << ", *pw = " << *pw << "\n\n";
cout << "ps = " << ps << ", *ps = " << *ps << endl;
ps += 1;
cout << "add 1 to the ps pointer:\n";
cout << "ps = " << ps << ", *ps = " << *ps << "\n\n";
cout << "access two elements with array notation\n";
cout << "stacks[0] = " << stacks[0] << ", stacks[1] = " << stacks[1] << endl;
cout << "acess two elements with pointer notation\n";
cout << "*stacks = " << *stacks << ", *(stacks + 1) = " << *(stacks + 1) << endl;
cout << sizeof(wages) << " = size of wages array\n";
cout << sizeof(pw) << " = size of pw pointer\n";
return 0;
}
输出结果:
程序清单 4.20
说明:目前认为 delete 只释放指针指向地址的 1 个元素(指针指向元素类型)大小的内存空间,而 delete [] 则意味着指针指向地址具有大于 1 个元素的分配地址空间;如果使用类似于 int *test = new int[1] 这样的方式,应该使用 delete 释放,因为其仅具有一个待释放的元素大小的空间
// ptrstr.cpp -- using pointer to strings
#include <iostream>
#include <cstring> // Declare strlen(), strcpy()
int main(void)
{
using namespace std;
char animal[20] = "bear"; // animal holds bear
const char *bird = "wren"; // bird holds address of string
char *ps; // Uninitialized
cout << animal << " and "; // Display bear
cout << bird << "\n"; // Display wren
// cout << ps << "\n"; // May display garbage, may cause a crash
cout << "Enter a kind of animal: ";
cin >> animal; // ok if input < 20 chars
// cin >> ps; // Too horrible a blunder to try; ps doesn't point to allocated space
ps = animal; // Set ps to point to string
cout << ps << "!\n"; // Ok, same as using animal
cout << "Before using strcpy():\n";
cout << animal << " at " << (int *)animal << endl;
cout << ps << " at " << (int *)ps << endl;
size_t size = strlen(animal) + 1;
ps = new char[size]; // Get new storage
strcpy_s(ps, size, animal); // copy string to new storage
cout << "After using strcpy():\n";
cout << animal << " at " << (int *)animal << endl;
cout << ps << " at " << (int *)ps << endl;
delete[] ps;
return 0;
}
输出结果:
程序清单 4.21
// newstrct.cpp -- using new with a structure
#include <iostream>
struct Inflatable { // Structure definition
char name[20];
float volume;
double price;
};
int main(void)
{
using namespace std;
Inflatable *ps = new Inflatable; // Allot memory for structure
cout << "Enter name of Inflatable item: ";
cin.get(ps->name, 20); // Method 1 for member access
cout << "Enter volume in cubic feet: ";
cin >> (*ps).volume; // Method 2 for member access
cout << "Enter price: $";
cin >> ps->price;
cout << "Name: " << (*ps).name << endl; // Method 2
cout << "Volume: " << ps->volume << " cubic feet\n"; // Method 1
cout << "Price: $" << ps->price << endl; // Method 1
delete ps; // Delete memory used by structure
return 0;
}
输出结果:
程序清单 4.22
// delete.cpp -- using the delete operator
#include <iostream>
#include <cstring>
using namespace std; // Or string.h
char *GetName(void); // Function prototype
int main()
{
char *name; // Create pointer but no storage
name = GetName(); // Assign address of string to name
cout << name << " at " << (int *)name << endl;
delete[] name; // Memory freed
name = GetName(); // Reuse freed memory
cout << name << " at " << (int *)name << endl;
delete[] name; // Memory freed again
return 0;
}
// Return pointer to new string
char *GetName(void)
{
char temp[80]; // Temp storage
cout << "Enter last name: ";
cin >> temp;
size_t size = strlen(temp) + 1;
char *pn = new char[size];
strcpy_s(pn, size, temp); // Copy string into smaller space
return pn; // Temp lost when function ends
}
输出结果:
程序清单 4.23
// mixTypes.cpp -- some type combinations
#include <iostream>
struct antarctica_years_end {
int year;
// Some really interesting data, etc.
};
int main()
{
antarctica_years_end s01 { }, s02 { }, s03 { };
s01.year = 1998;
antarctica_years_end *pa = &s02;
pa->year = 1999;
antarctica_years_end trio[3] { }; // Array of 3 structures
trio[0].year = 2003;
std::cout << trio->year << std::endl;
const antarctica_years_end *arp[3] = { &s01, &s02, &s03 };
std::cout << arp[1]->year << std::endl;
const antarctica_years_end **ppa = arp;
// Or use const antarctica_years_end **ppb = arp;
auto ppb = arp; // C++ 11 automatic type deduction
std::cout << (*ppa)->year << std::endl;
std::cout << (*(ppb + 1))->year << std::endl;
return 0;
}
输出结果:
程序清单 4.24
// choices.cpp -- array variations
#include <iostream>
#include <vector> // STL C++ 98
#include <array> // C++ 11
int main()
{
using namespace std;
// C, original C++
double a1[4] = { 1.2, 2.4, 3.6, 4.8 };
// C++ 98 STL
vector<double> a2(4); // Create vector with 4 elements
// No simple way to initialize in C98
a2[0] = 1.0 / 3.0;
a2[1] = 1.0 / 5.0;
a2[2] = 1.0 / 7.0;
a2[3] = 1.0 / 9.0;
// C++ 11 -- Create and initialize array object
array<double, 4> a3 = { 3.13, 2.72, 1.62, 1.41 };
array<double, 4> a4;
a4 = a3; // Valid for array objects of same size
// Use array notation
cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl;
cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl;
cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;
// Misdeed
a1[-2] = 20.2;
cout << "a1[-2]: " << a1[-2] << " at " << &a1[-2] << endl;
cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;
return 0;
}
输出结果:
编译警告:
编程练习题目
编程练习解答
题号 : 1
方法 :按要求输入并输出
示例代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Input
string firstName;
cout << "What is your first name? ";
getline(cin, firstName);
string lastName;
cout << "What is your last name? ";
getline(cin, lastName);
char grade;
cout << "What is your grade do you deserve? ";
cin >> grade;
int age;
cout << "What is your age? ";
cin >> age;
// Output
cout << "Name: " << lastName << ", " << firstName << endl;
cout << "Grade: " << ++grade << endl;
cout << "Age: " << age << endl;
return 0;
}
输出结果: