Solved

Attribute not recognized

Posted on 2003-11-27
29
544 Views
Last Modified: 2013-11-19
I have this problem:

i have a class named "Cliente",in the file cliente.h i have defined all attributes and methods for this class. The big part of method are method to set and get value of my attributes. now i have a method named "codiceFiscale" which is not recognized and the methods setCodiceFiscale and getCodiceFiscale not find or not recognized the codiceFiscale methods.

I attach the code below:


******************************cliente.h***********************
// Cliente.h

#ifndef CLIENTE_H
#define CLIENTE_H

#include <iostream>
#include <fstream>
#include <string>
#include "Date.h"
#include "CasellaInt.h"
#include "CasellaLong.h"
#include "CasellaTesto.h"

class Cliente {

public:

    Cliente();
   
    void setNome(string);
    void setCognome(string);
    void setVia(string);
    void setCap(long);
    void setCitta(string);
    void setProvincia(string);
    void setNazione(string);
    void setNumeroCartaCredito(string);
    void setNumeroNoleggiEffettuati(int);
    void setChilometriPercorsi(long);
    void setSpesaTotale(long);
    void setNumeroCivico(int);
    void setTarga(string);
    void setCodiceFiscale(string);
   
    long getCap();
    string getCodiceFiscale();
    long getSpesaTotale();
    int getNumeroCivico();
    long getChilometriPercorsi();
    int getNumeroNoleggi();
    string getNumeroCartaCredito();
    string getNazione();
    string getProvincia();
    string getCitta();
    string getVia();
    string getCognome();
    string getNome();
    string getTarga();
   
    void stampaCliente();
    void registraNoleggio(string);
    void inserisciDatiCliente();
    void leggiFileCliente(ifstream &);
    void scriviFileCliente(fstream &);


private:

    string codFis;
    long spesaTotale;
    int numeroCivico;
    long chilometriPercorsi;
    int numeroNoleggiEffettuati;
    string numeroCartaCredito;
    string nazione;
    string provincia;
    string citta;
    long cap;
    string via;
    string cognome;
    string targa;
    string nome;
};
#endif

*****end of cliente.h************************************************

******************************cliente.cpp***************************
// Cliente.cpp

#include "Cliente.h"
#include <stdlib.h>
#include <string>
#include <iomanip>
#include "Utility.h"
#include "Menu.h"

Cliente::Cliente()
{
    setNome("");
    setCognome("");
    setVia("");
    setCap(0);
    setCitta("");
    setProvincia("");
    setNazione("");
    setNumeroCartaCredito("");
    setNumeroNoleggiEffettuati(0);
    setChilometriPercorsi(0);
    setSpesaTotale(0);
    setCodiceFiscale("");
    setNumeroCivico(0);
    setTarga("");
}


// ***********Funzioni di Lettura***********

string Cliente::getNome(){
    return nome;
}

string Cliente::getCognome(){
    return cognome;
}

string Cliente::getVia(){
    return via;
}

long Cliente::getCap(){
    return cap;
}

int Cliente::getNumeroCivico(){
    return numeroCivico;
}

string Cliente::getCitta(){
    return citta;
}

string Cliente::getProvincia(){
    return provincia;
}
string Cliente::getNazione(){
    return nazione;
}

string Cliente::getNumeroCartaCredito(){
    return numeroCartaCredito;
}

int Cliente::getNumeroNoleggi(){
    return numeroNoleggiEffettuati;
}

long Cliente::getChilometriPercorsi(){
    return chilometriPercorsi;
}

long Cliente::getSpesaTotale(){
    return spesaTotale;
}

string Cliente::getCodiceFiscale(){
    return this->codFis;
}

string Cliente::getTarga(){
    return targa;
}

// *************Funzioni di Modifica***************

void Cliente::setCodiceFiscale(string cf){
  // this->codFis = cf; //Utility::maiuscola(cf);
}

void Cliente::setTarga(string t){
   // for(int i = 0; i < t.size(); i++)
     //   if(t.substr(i, 1) != " ")
     //       targa.append(t.substr(i, 1));
  //targa = Utility::maiuscola(t);
}

void Cliente::setNumeroCivico(int numeroCivico){
    numeroCivico = numeroCivico;
}

void Cliente::setSpesaTotale(long spesaTotale){
    spesaTotale = spesaTotale;
}

void Cliente::setChilometriPercorsi(long chilometriPercorsi){
   // this->chilometriPercorsi = chilometriPercorsi;  
}

void Cliente::setNumeroNoleggiEffettuati(int numeroNoleggiEffettuati){
   // this->numeroNoleggiEffettuati = numeroNoleggiEffettuati;
}

void Cliente::setNumeroCartaCredito(string numeroCartaCredito){
   numeroCartaCredito = numeroCartaCredito;
}

void Cliente::setNazione(string nazione){
   nazione = Utility::maiuscola(nazione);
}

void Cliente::setProvincia(string provincia){
   provincia = Utility::maiuscola(provincia);
}

void Cliente::setCitta(string citta){
   citta = Utility::maiuscola(citta);
}

void Cliente::setCap(long c){
   cap = c;
}

void Cliente::setVia(string via){
   via = Utility::maiuscola(via);
}

void Cliente::setCognome(string cognome){
   cognome = Utility::maiuscola(cognome);
}

void Cliente::setNome(string nome){    
   nome = Utility::maiuscola(nome);
}

// **********Funzione di gestione inserimento dati e gestione archivio**********

void Cliente::scriviFileCliente(fstream & file){
    file << this->getNome() << "|"
         << this->getCognome() << "|"
         << this->getCodiceFiscale() << "|"
         << this->getVia() << "|"
         << Utility::num2string(this->getNumeroCivico()) << "|"
         << Utility::num_long2string(this->getCap()) << "|"
         << this->getCitta() << "|"
         << this->getNazione() << "|"
         << this->getNumeroCartaCredito() << "|"
         << Utility::num2string(this->getNumeroNoleggi()) << "|"
         << Utility::num_long2string(this->getChilometriPercorsi()) << "|"
         << Utility::num_long2string(this->getSpesaTotale()) << "|"
         << this->getTarga() << "|";
         system("pause");
}

void Cliente::leggiFileCliente(ifstream & file){
    char buffer[100];
    string s;

    file.getline(buffer, 100, '|');
    s = buffer;
    this->setNome(s);
   
    file.getline(buffer, 100, '|');
    s = buffer;
    this->setCognome(s);

    file.getline(buffer, 100, '|');
    s = buffer;
    this->setCodiceFiscale(s);

    file.getline(buffer, 100, '|');
    s = buffer;
    this->setVia(s);
 
    file.getline(buffer, 100, '|');
    s = buffer;
    this->setNumeroCivico(Utility::string2int(s));
   
    file.getline(buffer, 100, '|');
    s = buffer;
    //this->setCap(Utility::string2long(s));
 
    file.getline(buffer, 100, '|');
    s = buffer;
    this->setCitta(s);

    file.getline(buffer, 100, '|');
    s = buffer;
    this->setNazione(s);
   
    file.getline(buffer, 100, '|');
    s = buffer;
    this->setNumeroCartaCredito(s);
   
    file.getline(buffer, 100, '|');
    s = buffer;
    this->setNumeroNoleggiEffettuati(Utility::string2int(s));
 
    file.getline(buffer, 100, '|');
    s = buffer;
    this->setChilometriPercorsi(Utility::string2long(s));
     
    file.getline(buffer, 100, '|');
    s = buffer;
    this->setSpesaTotale(Utility::string2long(s));
   
    file.getline(buffer, 100, '|');
    s = buffer;
    this->setTarga(s);
}

void Cliente::inserisciDatiCliente(){
    cout << Utility::riempimento(5, ' ')
         << "Inserisci tutti i dati relativi al cliente"
         << endl << endl;
         
    CasellaTesto codiceFiscaleC("\nInserisci il codice fiscale", "", "");
    codiceFiscaleC.setDato();
    this->setCodiceFiscale(codiceFiscaleC.getDato());
   
    CasellaTesto nomeC("\nNome  ", "", "");
    nomeC.setDato();
    this->setNome(nomeC.getDato());

    CasellaTesto cognomeC("\nCognome  ", "", "");
    cognomeC.setDato();
    this->setCognome(cognomeC.getDato());

    CasellaTesto viaC("\nVia  ", "", "");
    viaC.setDato();
    this->setVia(viaC.getDato());
   
    CasellaInt numeroCivicoC("\nNumero civico  ", "", "");
    numeroCivicoC.setDato();
    this->setNumeroCivico(numeroCivicoC.getDato());
   
    //CasellaLong capC("\nC.A.P.  ", "", "");
    //capC.setDato();
    //this->setCap(capC.getDato());
   
    CasellaTesto cittaC("\nCittà  ", "", "");
    cittaC.setDato();
    this->setCitta(cittaC.getDato());
   
    CasellaTesto nazioneC("\nNazione  ", "", "");
    nazioneC.setDato();
    this->setNazione(nazioneC.getDato());
   
    CasellaTesto numeroCartaCreditoC("\nNumero carta di credito  ", "", "");
    numeroCartaCreditoC.setDato();
    this->setNumeroCartaCredito(numeroCartaCreditoC.getDato());
}

void Cliente::registraNoleggio(string targaAffitto){}

void Cliente::stampaCliente(){
    system("cls");
    cout << endl;
    cout << setw(15) << "NOME      :" << this->getNome() <<"\n";
    cout << setw(15) << "COGNOME    :"<< this->getCognome() <<"\n\n";
    cout << setw(25) << "CODICE FISCALE      :"<<this->getCodiceFiscale() <<"\n";
    cout << setw(25) << "N°CARTA DI CREDITO      :"<<this->getNumeroCartaCredito() <<"\n\n";
    cout.unsetf(ios::left);
    cout << setw(25) << "Via      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getVia() << endl;
    cout.unsetf(ios::left);
    cout << setw(25) << "Numero civico      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getNumeroCivico() << endl;
    cout.unsetf(ios::left);
    cout << setw(25) << "C.A.P.      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getCap() << endl;
    cout.unsetf(ios::left);
    cout << setw(25) << "Città      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getCitta() << endl;
    cout.unsetf(ios::left);
    cout << setw(25) << "Provincia      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getProvincia() << endl;
    cout.unsetf(ios::left);
    cout << setw(25) << "Nazione      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getNazione() << endl;
    cout .unsetf(ios::left);
    cout << setw(25) << "N° noleggi effettuati      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getNumeroNoleggi() << endl;
    cout .unsetf(ios::left);
    cout << setw(25) << "Km percorsi      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getChilometriPercorsi() << endl;
    cout .unsetf(ios::left);
    cout << setw(25) << "Spesa Totale      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getSpesaTotale() << endl;
    cout .unsetf(ios::left);
    cout << setw(25) << "Targa      :";
    cout.setf(ios::left);
    cout << setw(10) << "      " << this->getTarga() << endl;
}

******************end of cliente.cpp*************************************
0
Comment
Question by:zprestaz
  • 12
  • 11
  • 3
  • +1
29 Comments
 
LVL 13

Expert Comment

by:SteH
Comment Utility
The version you posted of setCodiceFiscale is doing nothing since the definition contains only one line of comment. What else should it do?

void Cliente::setCodiceFiscale(string cf){
 // this->codFis = cf; //Utility::maiuscola(cf);
}

A method (=function?) called codiceFiscale I can't find in your class.

Why are you using getline with a char* and not the string version?
0
 

Author Comment

by:zprestaz
Comment Utility
i'm sorry,the attribute is named "codFis" and not "codiceFiscale"
setCodiceFiscale could set codFis,  i I have put like comment (the one line of code in setCodiceFiscale) because a problem on compilation......................this problem is get because codFis is not recognized and i don't know why.


0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
You need to have...

    using std::string;

...in your header file if you are not going to prefix string with std::
0
 

Author Comment

by:zprestaz
Comment Utility
I have added
                      using std::string;

but isn't this the solution

0
 
LVL 13

Expert Comment

by:SteH
Comment Utility
Does it get better with

using namespace std;
?

You don't have to use this-> inside a member function. It is automatically assumed, that class members are meant.

What is the error message? Could the error be on a line before already?
0
 

Author Comment

by:zprestaz
Comment Utility
Doesn't depend of this pointer. is true that inside a member function it's assumed,but isn't an error to use it explicitly

The problem isn't in compilation,excuse me, is in execution...........at the begin of execution.........
0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
> You don't have to use this-> inside a member function. It is automatically assumed, that class members are meant.

I hate seeing that too. Java programmers are taking over the world ;-)

zprestaz, can you include all your other headers so we can have comething which we can compile?

setCodiceFiscale looks OK to me, if you restore the commented code.

Try using the following and see what you can deduce:

--------8<--------
void Cliente::setCodiceFiscale(string cf){
  codFis = cf;
  std::cout << "Cliente Instance @" << std::hex << this << std::dec << ": setCodiceFiscale(" << cf << ")\n";
  // this->codFis = cf; //Utility::maiuscola(cf);
}
--------8<--------
0
 
LVL 13

Expert Comment

by:SteH
Comment Utility
For me it harms readibilty of the code using this without need.

It is a bit difficult to tell about a runtime error. We don't know from where the function is called, what the content of variables are at this time. Could you try to reduce the code and post all files necessary to reproduce the error? And still an error message might help. Or is the program just dying?
0
 

Author Comment

by:zprestaz
Comment Utility
ok , i have uploaded a zip file with all the project (dev-cpp 4.9.6.0 project) named GestioneAutonoleggio2.zip, take this and give me a solution please

go to --->http://xoom.virgilio.it
             click on login on the left
             user:ayamy_2
             psw:ayamy2
go to--->XOOM Sharehouse
go to--> i miei file (on the left)

that's all    

thanks very much
0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
I can appreciate why you didn't paste all the individual files in a comment.... :-)
0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
I'll take a proper look at this in a couple of hours time, when I get into the office, but in the meantime, I notice that your current code still has your codFis assignment commented out.
--------8<--------
void Cliente::setCodiceFiscale(string cf){
   ///codFis = Utility::maiuscola(cf);
   
}
--------8<--------

Can you confirm that enabling the assignment doesn't work?
--------8<--------
void Cliente::setCodiceFiscale(string cf){
   codFis = Utility::maiuscola(cf);
   
}
--------8<--------
0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
I've had a go at compiling the code on another compiler (GCC on Linux). There are quite a few things that the compiler complains about, must of which are not relevant - e.g. you haven't got using std::string in all the places required, but if your compiler compiles it OK, it must mean that it allows that. However, something that does rings alarm bells for me is that you are putting default parameters into your function implementations in the .cpp files.

e.g. Menu.cpp
--------8<--------
Menu::Menu( string o, string t ="", string dv = "20", string ev = "0")
   : sceltaUtente("Seleziona",dv,ev,"-1")
{
--------8<--------

In the case of Menu::Menu the default arguments are the same as the default aguments in Menu.h and I haven't found an example where they do not match, but it surprises me that your compiler doesn't throw up an error for this or at the least issues a warning.
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
Comment Utility
I made some efforts to get it compiled using my compiler (VC6) but i had no problems to uncomment

///codFis = Utility::maiuscola(cf);
    codFis = Utility::maiuscola(cf);

That compiles with no problems.

But my compiler found a bug in

void ArchivioClienti::leggiArchivio() {
    ifstream file;
    // char buffer[100];
    string categoria;
    file.open("ArchivioClienti.dat", ios::in | ios::trunc);
    // Cliente * cPtr;                         // THAT POINTER IS NEVER INITIALIZED
    Cliente * cPtr = new Cliente;       // THAT'S A GUESS
    if(file.good()) {
        while(!file.eof()) {
            cPtr->leggiFileCliente(file);
               // if(!ArchivioClienti::inserisciCliente(cPtr))    vedere se riaggiungerlo dopo aver sistemato codfis e cap
                //    cout << "Attenzione!!! Possibile perdita di dati! :(" << endl;
            }system("pause");
        }
        if(cPtr != NULL) {
           Mc.erase(cPtr->getCodiceFiscale());     //   ???????
        file.close();
        }
}

You should tell us, what problems you got.

Didn't it compile?
Did your program crash and where?
Didn't you get the results you expect?
Why did you comment the assignment to codFis?

A lot of questions but give us a chance.  ;-)

Regards, Alex
0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
OK, it works for me with GCC on Linux, with the following:

(1) I uncommented the assignment in Cliente.cpp:
--------8<--------
void Cliente::setCodiceFiscale(string cf){
   codFis = Utility::maiuscola(cf); /* This was previously commented out */
}
--------8<--------

(2) I replaced Client.cpp with my test stub test.cpp to test Cliente::setCodiceFiscale:
--------8<--------
#include "Cliente.h"
bool admin = true;
int main()
{
        Cliente c;
        c.setCodiceFiscale("Test");
        std::cout << "CodiceFiscale [" << c.getCodiceFiscale() << "]\n";
}
--------8<--------

(3) To get it to compile I added "using namespace std;" to several files and commented out all of the default parameter assignments in the .cpp files, fixed some filename case sensitivity issues (only relevant because it is Linux) and used the following Makefile:
--------8<--------
EXE=client

CCP=g++
CFLAGS=-Wno-deprecated -c
LFLAGS=

LOBJS= \
 ArchivioClienti.o\
 ArchivioVeicoli.o\
 BerlinaUtilitaria.o\
 Casella.o\
 CasellaFloat.o\
 CasellaInt.o\
 CasellaLong.o\
 CasellaTesto.o\
 Cliente.o\
 ControlloreClienti.o\
 Controllore.o\
 ControlloreInfo.o\
 ControlloreNoleggi.o\
 ControlloreVeicoli.o\
 Date.o\
 Epoca.o\
 Furgone.o\
 Lusso.o\
 Menu.o\
 Time.o\
 Utility.o\
 Veicolo.o \
 test.o
# Client.o ## Using test.cpp in place of Client.cpp

.SUFFIXES : .cpp .o

.cpp.o :
        $(CCP) $(CFLAGS) -o $@ $<

all:    $(EXE)

$(EXE) : $(LOBJS)
        $(CCP) $(LFLAGS) $(LOBJS) -o $@
--------8<--------

My output is (as expected):

       CodiceFiscale [TEST]

Whereabouts in your program is it not getting the expected assignment?
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
I expect that itsmeandnobodyelse has found your bug. I'm surprised and disappointed that GCC doesn't pick up on that when all warnings are enabled.

If I add -Wall to my CFLAGS to enable all warnings in GCC, I get *lots* of warnings about classes with virtual functions which do not have virtual destructors and the following, which you should probably check while you are at it:
--------8<--------
ArchivioClienti.cpp: In function `static void
   ArchivioClienti::leggiArchivio()':
ArchivioClienti.cpp:22: warning: unused variable `char buffer[100]'

CasellaFloat.cpp: In member function `virtual void CasellaFloat::isValid()':
CasellaFloat.cpp:18: warning: comparison between signed and unsigned integer
   expressions
CasellaFloat.cpp:15: warning: unused variable `int numdigits'
CasellaFloat.cpp:26: warning: value computed is not used

CasellaTesto.cpp:23: warning: comparison between signed and unsigned integer
   expressions

ControlloreClienti.cpp: In member function `virtual void
   ControlloreClienti::stampaListaClienti(std::vector<Cliente*,
   std::allocator<Cliente*> >)':
ControlloreClienti.cpp:175: warning: comparison between signed and unsigned
   integer expressions
ControlloreClienti.cpp:206: warning: comparison between signed and unsigned
   integer expressions

ControlloreVeicoli.cpp:226: warning: comparison between signed and unsigned
   integer expressions

Menu.cpp: In constructor `Menu::Menu(std::basic_string<char,
   std::char_traits<char>, std::allocator<char> >, std::basic_string<char,
   std::char_traits<char>, std::allocator<char> >, std::basic_string<char,
   std::char_traits<char>, std::allocator<char> >, std::basic_string<char,
   std::char_traits<char>, std::allocator<char> >)':
Menu.cpp:16: warning: comparison between signed and unsigned integer
   expressions
Menu.cpp: In member function `bool Menu::valutaOpzione()':
Menu.cpp:33: warning: comparison between signed and unsigned integer
   expressions
Menu.cpp: In member function `void Menu::setSceltaUtente(bool, bool)':
Menu.cpp:60: warning: comparison between signed and unsigned integer
   expressions

Utility.cpp: In static member function `static std::string
   Utility::num2string(int)':
Utility.cpp:14: warning: format argument is not a pointer (arg 3)

Veicolo.cpp: In member function `void Veicolo::setTarga(std::basic_string<char,
   std::char_traits<char>, std::allocator<char> >)':
Veicolo.cpp:55: warning: comparison between signed and unsigned integer
   expressions
Veicolo.cpp: In member function `virtual float
   Veicolo::calcolaPreventivo(Date&, Date&)':
Veicolo.cpp:139: warning: control reaches end of non-void function
--------8<--------
0
 

Author Comment

by:zprestaz
Comment Utility
I've see your comment:

*
this is commented .........
--------8<--------
void Cliente::setCodiceFiscale(string cf){
   ///codFis = Utility::maiuscola(cf);
   
...........only for test the code and understand that the problem is there,such as in

void Cliente::setTarga(string t){
   // for(int i = 0; i < t.size(); i++)
     //   if(t.substr(i, 1) != " ")
     //       targa.append(t.substr(i, 1));
  //targa = Utility::maiuscola(t);
}

i have understand ,testing the code that,   codFis is an attribute not recognized

the problem is in run time


** i have tested that my project is ok ,parts such as veicolo.cpp .h are ok
    veicolo.cpp and cliente.cpp are similar,but only veicolo run well

***
Didn't it compile?..........it compile,but in run time,after the login, the program goes on error and stops run
Did your program crash and where?...........my program crash at the initial of run time,when i call        ArchivioClienti::leggiArchivio();   because codFis is not recognized
Didn't you get the results you expect?   because of this reasons i have commented  ///codFis = Utility::maiuscola(cf);  only for test the code
Why did you comment the assignment to codFis?

0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
> my program crash at the initial of run time,when i call ArchivioClienti::leggiArchivio(); because codFis is not recognized

No... Surely it is because the bug pointed out by itsmeandnobodyelse in ArchivioClienti::leggiArchivio....

>     // Cliente * cPtr;                         // THAT POINTER IS NEVER INITIALIZED
0
 

Author Comment

by:zprestaz
Comment Utility
>No... Surely it is because the bug pointed out by itsmeandnobodyelse in >ArchivioClienti::leggiArchivio....

>     // Cliente * cPtr;                         // THAT POINTER IS NEVER INITIALIZED

in which file and function???
0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
ArchivioClienti.cpp Line 25.

--------8<--------
void ArchivioClienti::leggiArchivio() {
    ifstream file;
    char buffer[100];
    string categoria;
    file.open("ArchivioClienti.dat", ios::in | ios::nocreate);
    Cliente * cPtr;                   // <------- THAT POINTER IS NEVER INITIALIZED
    if(file.good()) {
        while(!file.eof()) {
            cPtr->leggiFileCliente(file);
               // if(!ArchivioClienti::inserisciCliente(cPtr))    vedere se riaggiungerlo dopo aver sistemato codfis e cap
                //    cout << "Attenzione!!! Possibile perdita di dati! :(" << endl;
            }system("pause");
        }
        if(cPtr != NULL) {
           Mc.erase(cPtr->getCodiceFiscale());     //   ???????
        file.close();
        }
}
--------8<--------
0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
Please credit this to Alex (itsmeandnobodyelse) - it was his discovery.
0
 

Author Comment

by:zprestaz
Comment Utility
ok, but with whitch value................with null the problem is the same
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
Comment Utility
I made a suggestion:

    Cliente * cPtr = new Cliente;  
    // That would be good, if you want to create a new instance of type Cliente here.

    // Just in case you already have some valid client somewhere  (means that you had a statement like
    // 'Cliente * cPtr = new Cliente; ' somewhere else then you should get it here

    Cliente * cPtr = getClienteFromSomewhere();

With a NULL pointer it crashes because of

           cPtr->leggiFileCliente(file);

if cPtr is not initialized it might crash later - for example in setCodiceFiscale() because the ppointer points to some invalid memory.

Regards, Alex



   
0
 

Author Comment

by:zprestaz
Comment Utility
ok i'll try later because now i have to go out,,,,
when done i'll credit you..........

0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
Cliente::eggiFileCliente is supported to initialise Cliente object from file. It needs the Cliente object to be allocated.

Alex's suggestion is:

   Cliente * cPtr = new Cliente;

This looks good to me.

However, I can't see that you are doing anything with the Cliente objects, when they are initialised by the file in your....

    while(!file.eof()) {
            cPtr->leggiFileCliente(file);
               // if(!ArchivioClienti::inserisciCliente(cPtr))    vedere se riaggiungerlo dopo aver sistemato codfis e cap
                //    cout << "Attenzione!!! Possibile perdita di dati! :(" << endl;
     }

...loop.

Also you ought to delete cPtr at the end of your function.

I notice that the commented out ArchivioClienti::inserisciCliente(cPtr) does the following:

  bool ArchivioClienti::inserisciCliente(Cliente * c) {
    if((presente(c->getCodiceFiscale())) || ((c->getCodiceFiscale()).size() != 16))
        return false;
    else {
        Mc[c->getCodiceFiscale()] = c;
        return true;
    }
  }

If the Mc[] array is supposed to retain pointers to instances of Cliente initialised from the file by Cliente::leggiFileCliente, you shouldn't delete these pointers, but on the same token, you should ensure that new instances of Cliente are initialised for other members of the array.

Have you inherited this code from another developer?
0
 

Author Comment

by:zprestaz
Comment Utility
Problem not solved
0
 

Author Comment

by:zprestaz
Comment Utility
In your opinion, can i remediate to this problem without use of pointers on cliente,just using a cliente's object like parameter?
0
 
LVL 17

Expert Comment

by:rstaveley
Comment Utility
It depends what you are trying to achieve. Do you want to keep copies if instances of Cliente in the Mc[] array?
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 50 total points
Comment Utility
The static function  ArchivioClienti::leggiArchivio() is called once in Controllore::eseguiApplicazione(), and if am right in the initialization part of the application. It looks like loading clients from a previous session, BUT there are some big mistakes if this was the intention:

First, the pointer was not initialized and that is why the program crashes. I suggested
     
        Cliente * cPtr = new Cliente;    

when the pointer was defined. But i was wrong, because the file may contain more than one cliente - as you could see from ArchivioClienti::scriviArchivio(). Therefore the statement 'cPtr = new Cliente' must be moved to run within loop, thus getting an instance of any archived client. Next, the commented statement

        if(!ArchivioClienti::inserisciCliente(cPtr))    ...

should be uncommented to fill the map Mc and last, the part

       if(cPtr != NULL) {
           Mc.erase(cPtr->getCodiceFiscale());     //   ???????

must be removed because it would delete any cliente from the map just read and then the function makes no sense.

All said leads to

void ArchivioClienti::leggiArchivio() {
    ifstream file;
    file.open("ArchivioClienti.dat", ios::in | ios::trunc);
    Cliente * cPtr = NULL;        // try to initialize pointers to not getting unpredictable results
                                            // with NULL and forgetting to create an instance you'll crash immediately
                                            // if you don't initialize your program will crash somewhere but not necesseraly at the next call
    if(file.good()) {
        while(!file.eof()) {
            cPtr = new Cliente;    // make a new instance when successfully read a cliente
            cPtr->leggiFileCliente(file);

            // the next statement was commented - maybe because it has crashed here because of the missing 'new Cliente'
            // it will store the pointer to a map that is supposed to hold all registered clients
            if(!ArchivioClienti::inserisciCliente(cPtr))    vedere se riaggiungerlo dopo aver sistemato codfis e cap
            {
                 cout << "Attenzione!!! Possibile perdita di dati! :(" << endl;
                 system("pause");
             }
             // All ok! we should not delete the pointer because the object lives
             // And we shouldn't remove the pointer from map because that was the only purpose of this function
        }
        file.close();
     }
}

Hope, that helps

Alex
0
 

Author Comment

by:zprestaz
Comment Utility
thank you alex
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Preface This article introduces an authentication and authorization system for a website.  It is understood by the author and the project contributors that there is no such thing as a "one size fits all" system.  That being said, there is a certa…
This article covers the basics of the Sass, which is a CSS extension language. You will learn about variables, mixins, and nesting.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now