Home > Software engineering >  Print number in front of every line of a file
Print number in front of every line of a file

Time:12-23

I have made a phone book and the function to add users. I want it to have numbers in front of every line, but I get the wrong number in front of each line. I have added code that prints out the numbers but it gives a big number that is the same on every line. I want it to print like this:

1 John Doe
2 Johnny Doe
3 Max Doe

Right now, it prints this instead:

1878003873 John Doe
1878003873 Johnny Doe
1878003873 Max Doe

I don't know where that number comes from.

void addContact()
{
    string Fname, Lname, Address, Contact, list, name, Fname2, Lname2, Address2, Contact2;
    int counter, number;
    cout << "Enter First Name: ";
    getline(cin, Fname);
    cout << "Enter Last Name: ";
    getline(cin, Lname);
    cout << "Enter Address: ";
    getline(cin, Address);
    cout << "Enter Contact Number: ";
    getline(cin, Contact);

    ifstream asd("number.txt");
    while (asd >> counter >> Fname2 >> Lname2 >> Address2 >> Contact2)
    {
        number = counter;
    }
    ofstream adb("number.txt", ios::app);
    number = number   1;
    adb << number << " " << Fname << " " << Lname
        << " " << Address << " " << Contact << endl;
}

CodePudding user response:

Suppose that you are adding your first user. What do you think that value of number is going to be then?

ifstream asd("number.txt");
while (asd >> counter >> Fname2 >> Lname2 >> Address2 >> Contact2)
{
    number = counter;
}

Because it is your first user then while loop is never entered, so number is never initialised. Hence the garbage numbers you see. Once the first garbage number is there, then the code correctly adds one to each following number.

To fix just add this so that number always gets an initial value.

int counter, number = 0;

Not what you asked about but I think you should close your input file before you try to write the new user

ifstream asd("number.txt");
while (asd >> counter >> Fname2 >> Lname2 >> Address2 >> Contact2)
{
    number = counter;
}
asd.close(); // stop reading and close the input file
ofstream adb("number.txt", ios::app);
...

Having a reading and a writing stream open simultaneously on the same file is not a good idea, even if it does seem to work in this case.

  •  Tags:  
  • c
  • Related