1

What I do here is convert my input name to char then check from the text file if char a which is the input name exists or equal to existing nameData. nameData is the variable stored in the text file. But my program crashed once it detects that the input is new. What may seemed the problem in this problem? I'm getting the crash from else condition part.

char *nameData;
    char *passData;
    QByteArray nameBa;
    nameBa = name.toLatin1();
    nameData = nameBa.data();
    passData = pass.data();

    char *a;
    QByteArray aBa;
    aBa = name.toLatin1();
    a = aBa.data();

    std::fstream dataProfile;
    dataProfile.open("D:/Data.txt", std::ios::in);

while(!dataProfile.eof())
    {
        dataProfile.getline(nameData, 90, ' ');
        dataProfile.getline(passData, 90);
        if(std::strcmp(nameData, a)==0)
        {
           std::cout << "Profile Already exists\n";
           //if break here, still crash to else condition
        }
        else
        {
            std::cout << "Not Exists\n";
        }
        break;
    }
  • Possible duplicate of [Why is “while (!feof(file))” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) – mch Mar 07 '19 at 08:42
  • Are you sure with the `break;` at the end of the `while`? That makes the `while` to an `if`. – mch Mar 07 '19 at 08:43

2 Answers2

3

char *nameData; and char *passData; are not allocated with memory. you need to pre-allocated memory like this : http://www.cplusplus.com/reference/istream/istream/getline/

char name[256], title[256];

std::cout << "Please, enter your name: ";
std::cin.getline (name,256);

std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256);
Fryz
  • 2,119
  • 2
  • 25
  • 45
alon
  • 220
  • 1
  • 16
1

I already figured it out, what I did is:

char nameData[90];
char passData[90];
strcpy(nameData, name.toStdString().c_str()); //name is string
strcpy(passData, pass.data()); //pass is bytearray