// This function fills in a Person message based on user input. voidPromptForAddress(tutorial::Person* person){ cout << "Enter person ID number: "; int id; cin >> id; person->set_id(id); cin.ignore(256, '\n');
cout << "Is this a mobile, home, or work phone? "; string type; getline(cin, type); if (type == "mobile") { phone_number->set_type(tutorial::Person::MOBILE); } elseif (type == "home") { phone_number->set_type(tutorial::Person::HOME); } elseif (type == "work") { phone_number->set_type(tutorial::Person::WORK); } else { cout << "Unknown phone type. Using default." << endl; } } }
// Main function: Reads the entire address book from a file, // adds one person based on user input, then writes it back out to the same // file. intmain(int argc, char* argv[]){ // Verify that the version of the library that we linked against is // compatible with the version of the headers we compiled against. GOOGLE_PROTOBUF_VERIFY_VERSION;
{ // Read the existing address book. fstream input(argv[1], ios::in | ios::binary); if (!input) { cout << argv[1] << ": File not found. Creating a new file." << endl; } elseif (!address_book.ParseFromIstream(&input)) { cerr << "Failed to parse address book." << endl; return-1; } }
// Add an address. PromptForAddress(address_book.add_people());
{ // Write the new address book back to disk. fstream output(argv[1], ios::out | ios::trunc | ios::binary); if (!address_book.SerializeToOstream(&output)) { cerr << "Failed to write address book." << endl; return-1; } }
// Optional: Delete all global objects allocated by libprotobuf. google::protobuf::ShutdownProtobufLibrary();
// Iterates though all people in the AddressBook and prints info about them. voidListPeople(const tutorial::AddressBook& address_book){ for (int i = 0; i < address_book.people_size(); i++) { const tutorial::Person& person = address_book.people(i);
switch (phone_number.type()) { case tutorial::Person::MOBILE: cout << " Mobile phone #: "; break; case tutorial::Person::HOME: cout << " Home phone #: "; break; case tutorial::Person::WORK: cout << " Work phone #: "; break; } cout << phone_number.number() << endl; } } }
// Main function: Reads the entire address book from a file and prints all // the information inside. intmain(int argc, char* argv[]){ // Verify that the version of the library that we linked against is // compatible with the version of the headers we compiled against. GOOGLE_PROTOBUF_VERIFY_VERSION;