简体   繁体   中英

Program Crash on C++ regarding checking if data exists

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;
    }

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM