当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Why does using strcmp in this situation crash my program?

问题描述:

I'm having difficulties using strcmp. I make a call in a separate else statement (not listed), and it works fine. Is this a possible memory issue?

while(inHere == 1)

{

int numberOfOccupiedTables = 0;

cout << "\nSelect a table below\n---------------\n\n";

for(int i = 0; i < tables->size(); i++)

{

if(tables->at(i)->open == 0)

{

cout << "Table " << tables->at(i)->value << "\n";

numberOfOccupiedTables++;

}

}

if(numberOfOccupiedTables == 0)

cout << "No customers found.\n";

else

{

cout << "(q to back out) Enter number of table: ";

char* choice = (char*)malloc(sizeof(char)*256);

fgets(choice,256,stdin);

if(strcmp(choice, "q\n") == 0)

inHere = 0;

}

网友答案:

If fgets() fails because it reached the end of the file, it will not add a null terminator to the string. Check to make sure it hasn't returned NULL before you do the strcmp().

分享给朋友:
您可能感兴趣的文章:
随机阅读: