1 // See README.txt for information and build instructions.
6 #include "addressbook.pb.h"
9 // This function fills in a Person message based on user input.
10 void PromptForAddress(tutorial::Person
* person
) {
11 cout
<< "Enter person ID number: ";
15 cin
.ignore(256, '\n');
17 cout
<< "Enter name: ";
18 getline(cin
, *person
->mutable_name());
20 cout
<< "Enter email address (blank for none): ";
24 person
->set_email(email
);
28 cout
<< "Enter a phone number (or leave blank to finish): ";
35 tutorial::Person::PhoneNumber
* phone_number
= person
->add_phones();
36 phone_number
->set_number(number
);
38 cout
<< "Is this a mobile, home, or work phone? ";
41 if (type
== "mobile") {
42 phone_number
->set_type(tutorial::Person::MOBILE
);
43 } else if (type
== "home") {
44 phone_number
->set_type(tutorial::Person::HOME
);
45 } else if (type
== "work") {
46 phone_number
->set_type(tutorial::Person::WORK
);
48 cout
<< "Unknown phone type. Using default." << endl
;
53 // Main function: Reads the entire address book from a file,
54 // adds one person based on user input, then writes it back out to the same
56 int main(int argc
, char* argv
[]) {
57 // Verify that the version of the library that we linked against is
58 // compatible with the version of the headers we compiled against.
59 GOOGLE_PROTOBUF_VERIFY_VERSION
;
62 cerr
<< "Usage: " << argv
[0] << " ADDRESS_BOOK_FILE" << endl
;
66 tutorial::AddressBook address_book
;
69 // Read the existing address book.
70 fstream
input(argv
[1], ios::in
| ios::binary
);
72 cout
<< argv
[1] << ": File not found. Creating a new file." << endl
;
73 } else if (!address_book
.ParseFromIstream(&input
)) {
74 cerr
<< "Failed to parse address book." << endl
;
80 PromptForAddress(address_book
.add_people());
83 // Write the new address book back to disk.
84 fstream
output(argv
[1], ios::out
| ios::trunc
| ios::binary
);
85 if (!address_book
.SerializeToOstream(&output
)) {
86 cerr
<< "Failed to write address book." << endl
;
91 // Optional: Delete all global objects allocated by libprotobuf.
92 google::protobuf::ShutdownProtobufLibrary();