1

I have this code:

try{
    ifstream file("Students.txt", ios::in);
    if (!file) throw MyExceptions();
    int begin = file.tellg();
    file.seekg (0, ios::end);
    int end = file.tellg();
    int size =  end - begin;
    char *charField;
    int numFields = 0, charNumber = 0;
    CustomString studentCode, secondName, firstName;

    while (file.getline(charField, size, ',')) {
        while(*charField == ','){
            charNumber++;
            charField++;
        }

        int tmpCharNumber = charNumber;

        while(tmpCharNumber > 0){
            tmpCharNumber--;
            charField--;
        }

        if (numFields == 0){
            studentCode = CustomString(charField, charNumber);
            numFields++;
        }else if (numFields == 1){
            secondName = CustomString(charField, charNumber);                
            numFields++;
        }else if (numFields == 2){
            firstName = CustomString(charField, charNumber);        
            numFields = 0;
        }
        firstName.PrintData();
        secondName.PrintData();
        studentCode.PrintData();
    }

    file.close();   
}catch(MyExceptions e){

}

And this file:

SR000001,EPONYMO 0001,ONOMA 0001
SR000002,EPONYMO 0002,ONOMA 0002
SR000003,EPONYMO 0003,ONOMA 0003

I get this error on the while statement:

RUN FAILED (exit value -1,073,741,819, total time: 3s)

Any suggestion?

I do not understand where the error is? Should I use any library?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 4
    `char *charField;` where did you allocate memory for this? You have a pointer that has never been initialized. – drescherjm Jun 10 '20 at 17:31
  • 3
    That's one more reason to use `std::string` - it manages the memory for you. – Lukas-T Jun 10 '20 at 17:32
  • 3
    When you see a batsmurf crazy number like -1,073,741,819, convert it to hex and see if it becomes more recognizable. 0xC0000005 is commonly used as a code for Access Violation, trying to access (read or write) a memory location not assigned to your process. Usually this is the result of a bad pointer, so the first thing you should look for next time you see this code is a pointer that's uninitialized. – user4581301 Jun 10 '20 at 17:48
  • 1
    If everything looks safely initialized, start looking for pointers that have been initialized, but initialized to `NULL` or `nullptr` and never changed. If you can't find any of those, look for pointers to dynamic allocations that may have been freed.prematurely. After you've checked all of those possibilities pull out the debugger and go spelunking. Either you missed something or you've got a sneaky son of a gun that's going to take some detective work. – user4581301 Jun 10 '20 at 17:48
  • 4
    "_Should I use any library?_" - Yes, `#include` and use `std::string` and `std::getline()` from the standard library. – Ted Lyngmo Jun 10 '20 at 17:53

0 Answers0