0

I am trying to create a phonebook using CPP and filesystem method. When I enter the 10 digit phone number, it gets stored as some other random number than the input number. However, when I enter numbers uptill 9 digits, it gets stored and outputs perfectly. Why is this change happening only in 10 digit number?

I have even tried changing the data type of 'number' variable like int, long int, double, float, but to no avail.

This is my code:

class Phonebook
{
public:
    Phonebook()
    {
        number = 0;
    }
    void getdata();
    void addtofile();
    void display();
    ~Phonebook() {}
private:
    long int number;
    string name;
};

void Phonebook::getdata()
{
    cout << "Enter contact name: ";
    cin >> name;
    cout << "\nEnter contact number: ";
    cin >> number;
}

void Phonebook::addtofile()
{
    ofstream fout;
    fout.open("phonebook.txt");
    fout << name << " " << number;
    fout.close();
}

void Phonebook::display()
{
    ifstream fin;
    fin.open("phonebook.txt");
    cout << endl << "name: " << name << endl << "number: " << number;
}

void main()
{
    Phonebook p;
    p.getdata();
    p.addtofile();
    p.display();
}

Output when a user enters a 10 digit number: output screenshot for 10 digit number

Output when a user enters a 9 digit number: output screenshot for 9 digit number

How to fix this? Please help

ProxyHydra
  • 11
  • 4
  • 1
    Overflow (2,147,483,647 is 0x7FFFFFFF). Hold phone numbers as text (std::string) not integers (consider international). – Richard Critten Jan 30 '21 at 10:12
  • 1
    Does this answer your question? [Unable to Count Number of Digits as the Input](https://stackoverflow.com/questions/25925241/unable-to-count-number-of-digits-as-the-input) – outis Jan 30 '21 at 10:23

1 Answers1

0

Consider phone number belongs to same city or region you are! as 6 up 9 digits integer number! But when phone number belongs other city or country, and it starts with one 0 or 00 or + sign, how you read/write it as number!

change number from long int to string!

Ali Razmkhah
  • 280
  • 1
  • 10