Program Create Phone Record File

By | March 26, 2024

Program Create Phone Record File – Write a C++ program to input phone records and write into phone file. The program will ask the user “Do you want to add more records (y/n) ?. It will input phone records as long as the user will enter a ‘y’.

Source Code

#include <iostream>
#include <fstream>

using namespace std;

// Define the structure
struct Phone {
    char name[30];
    char phone[20];
};

int main() {
    
	Phone prec;
	// Create a binary file for writing
    fstream file1("d://phonefile.dat", ios::binary | ios::app);
    if (!file1) {
        cout << "Error: Unable to open file." << endl;
        return 1;
    }

    char choice = 'y';
    while (choice == 'y') {
        // Input Phone record
        cout << "Enter Name: ";
        cin.getline(prec.name,30);
        //cin.ignore(); // Ignore newline character left in the input buffer
        cout << "Enter Phone: ";
        cin.getline(prec.phone, 20);
        
        // Write the record into the file
        file1.write((char*)&prec, sizeof(prec));
        
        cout << "Do you want to add more records? (y/n): ";
        cin >> choice;
        cin.ignore(); // Ignore newline character left in the input buffer
    }

    // Close the file
    file1.close();

    return 0;
}

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *