0

I would like some help with the following code/agenda, every time you edit/delete the agenda and index, it adds an additional "endl;" to "Agenda.txt" and since there is a new line without a index reference, the "Index.txt" saves a "-858993460" as recorded number caused from the new empty line in the agenda caused by editing the file, if you add contacts works fine.

The code is basically in spanish but I commented main instructions. Please help!

#include <conio.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <math.h>
using namespace std;

struct estudiantes
{
    int telefono;
    char nombre[50];
};

estudiantes contacto[100];

int main()
{

    int opciones, i;
    ifstream readagenda, readindex;

    do
    {
        system("cls");
        cout << "Elige opcion a ejecutar" << endl;
        cout << "1. Verificar agenda de contactos actual" << endl; //view current agenda
        cout << "2. Agregar contactos" << endl; //Add contact numbers
        cout << "3. Editar contactos" << endl; //Edit contacts
        cout << "4. Eliminar contactos" << endl; //Erase contacts 
        cout << "5. Terminar Programa" << endl; //End program
        cout << "Ingrese # opcion a elegir: ";
        cin >> opciones;
        switch (opciones)
        {

        case 1:
        {
            char linea[100];
            cout << endl;
            readagenda.open("Agenda.txt", ios::in);
            if (readagenda.fail())
            {
                cout << "No se puede abrir el archivo, ingresa contactos para crear una agenda" << endl;
            }
            else
            {
                do
                {
                    readagenda.getline(linea, sizeof(linea));
                    cout << linea << endl;
                } while (!readagenda.eof());
            }

            readagenda.close();
            system("Pause");
            break;
        }
        case 2:
        {
            ofstream add, index;
            int contactos;

            cout << "\nIngrese Cantidad de contactos a guardar : ";//how many contacts are you going to save?
            cin >> contactos;

            for (int i = 1; i <= contactos; i++)
            {

                cout << "Ingrese Telefono No. " << i << " : ";//phone number
                cin >> contacto[i].telefono;
                cin.ignore(256, '\n');
                cout << "Ingrese Nombre " << i << " : ";//full name
                cin.getline(contacto[i].nombre, sizeof(contacto[i].nombre), '\n');
            }

            add.open("Agenda.txt", ios::app);

            if (add.fail())
            {
                cout << "\nNo se puede crear el archivo" << endl;
                exit(1);
            }

            for (int i = 1; i <= contactos; i++)
            {
                add << contacto[i].telefono << " - " << contacto[i].nombre << endl;
            }
            add.close();

            index.open("Index.txt", ios::app);
            if (index.fail())
            {
                cout << "\nNo se puede crear el archivo" << endl;
                exit(1);
            }

            for (int i = 1; i <= contactos; i++)
            {
                index << contacto[i].telefono << endl;
            }

            index.close();

            cout << "\nContacto agregado exitosamente...";//contact added
            system("pause");
            break;
        }
        case 3:
        {
            int modificar, readnum[100];
            char newname[100], readcon[100];
            i = 0;
            bool encontrado = false;
            cout << "\nIngrese No. telefono de contacto a modificar: ";//contact to modify
            cin >> modificar;
            cin.ignore(256, '\n');
            cout << "Ingrese nuevo nombre de contacto: "; //new contact name
            cin.getline(newname, sizeof(newname), '\n');
            ofstream numerosmodtemp;
            readindex.open("Index.txt", ios::in); // opens index
            readagenda.open("Agenda.txt", ios::in); // opens agenda
            numerosmodtemp.open("numerosmodtemp.txt", ios::app); //creates temp file
            if (readagenda.fail() || readindex.fail())
            {
                cout << "\nNo se puede abrir el archivo, ingresa contactos para crear una agenda" << endl;
            }
            else
            {
                do
                {
                    readagenda.getline(readcon, sizeof(readcon)); // reads agenda
                    readindex >> readnum[i]; // reads index
                    if (readnum[i] == modificar)
                    {
                        encontrado = true;
                        numerosmodtemp << modificar << " - " << newname << endl;//adds new contact info
                    }
                    else
                    {
                        numerosmodtemp << readcon << endl; // uses regular agenda
                    }
                    i++;
                } while (!readindex.eof());
                numerosmodtemp.close();
                readindex.close();
                readagenda.close();
                if (encontrado == true)
                {
                    cout << "\nContacto modificado exitosamente..."; // contact edited
                    system("pause");
                }
                else
                {
                    cout << "\nContacto no ha sido encontrado..."; //contact not found
                    system("pause");
                }
                remove("Agenda.txt");
                rename("numerosmodtemp.txt", "Agenda.txt");
                break;
            }
            break;
        }
        case 4:
        {
            int borrar, readn[100];
            char readc[100];
            i = 0;
            bool encontrado = false;
            cout << "\nIngrese No. telefono de contacto a eliminar: ";//number of contact to erase
            cin >> borrar;
            ofstream numerosborrados, numerosdeltemp, numerostemp;
            readindex.open("Index.txt", ios::in); // opens index
            readagenda.open("Agenda.txt", ios::in); // opens agenda
            numerosborrados.open("Contactos Borrados.txt", ios::app); // opens erased contacts
            numerosdeltemp.open("numerosdeltemp.txt", ios::app); // opens temp index
            numerostemp.open("numerostemp.txt", ios::app); // opens temp agenda
            if (readagenda.fail() || readindex.fail())
            {
                cout << "\nNo se puede abrir el archivo, ingresa contactos para crear una agenda" << endl;
            }
            else
            {
                do
                {
                    readagenda.getline(readc, sizeof(readc)); // reads contacts
                    readindex >> readn[i]; // reads index
                    if (readn[i] == borrar)
                    {
                        encontrado = true;
                        numerosborrados << readc << endl; // adds to erased contacts file
                    }
                    else
                    {
                        numerostemp << readc << endl; // adds to temp agenda
                        numerosdeltemp << readn[i] << endl; // adds to temp index
                    }
                    i++;
                }while (!readindex.eof());
            }
            numerosborrados.close();
            numerostemp.close();
            numerosdeltemp.close();
            readindex.close();
            readagenda.close();
            if (encontrado == true) 
            {
                cout << "\nContacto eliminado exitosamente...";// contact erased
                system("pause");
            }
            else
            {
                cout << "\nContacto no ha sido encontrado..."; //contact not found
                system("pause");
            }
            remove("Agenda.txt"); 
            remove("Index.txt");
            rename("numerosdeltemp.txt", "Index.txt");
            rename("numerostemp.txt", "Agenda.txt");
            break;
        }
        case 5:
        {
            cout << "\nPrograma terminado, "; // End program
            system("pause");
            break;
        }
        default:
        {
            cout << "\nEsta opcion no esta disponible, "; // not available
            system("pause");
            break;
        }
        }
    } while (opciones != 5);
}
  • 1
    `-858993460` = `0xcccccccc` which is uninitialized stack memory. https://stackoverflow.com/a/127404/487892 – drescherjm Mar 13 '19 at 04:22
  • yes, how do I make the code to ignore that line from index when reading the archive if is null, I tried with multiple ifs.. while.. and continues adding the heap data to the new temp file when reading the "txt" – Luis Diego Castillo Mar 13 '19 at 04:24
  • `for (int i = 1; i <= contactos; i++)` I am not sure this is correct. Remember array indices start at 0 not 1. – drescherjm Mar 13 '19 at 04:25
  • I think you posted way too much code for a [mcve] – drescherjm Mar 13 '19 at 04:26
  • `}while (!readindex.eof());` is probably a bug for the same reason as this question: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – drescherjm Mar 13 '19 at 04:27
  • correct, but that "i=0" is to read contacts only, Im having trouble with case 3 and 4 only, and I indice "i=0" in those cases, you might be right about adding too much code, sorry for that, try to compile and test the c++ to see what I get when editing or deleting a contact. – Luis Diego Castillo Mar 13 '19 at 04:30
  • I figured out could be something like related to the index.eof(), I just tried to changed the do while as states in the link you shared but now is deleting another contacts that shouldnt, here is my updated code, I tried while and do while `while (readindex >> readn[i]){` – Luis Diego Castillo Mar 13 '19 at 04:51
  • You'd be surprised what invoking undefined behaviour can do to a program. Very often where the bug becomes visible and where it actually occurs in the code have no obvious relationship. – user4581301 Mar 13 '19 at 05:42
  • You are right, .eof() seems is ambiguous, I was able to fix the issue by changing `while (!readindex.eof())` to `while (!(readindex >> std::ws).eof())` Thank you both! – Luis Diego Castillo Mar 13 '19 at 05:52

0 Answers0