progam在std :: getline AM之后停止响应,代码中是否存在错误

progam stop responding after std::getline am is there a mistake in the code?

本文关键字:代码 是否 存在 响应 错误 std getline AM progam 之后      更新时间:2023-10-16

添加名称(nome)并按Enter Enter the progam关闭我已经尝试使用的progam代码的一部分在下面

aux1 = (struct no *) malloc(sizeof(struct no)+1);
printf("nnDigite numero a ser inserido: ");
gets(auxitem);
aux1->numero = atoi(auxitem);
printf("nnDigite o nome do contato ser inserido: ");
std::getline(std::cin, aux1->nome);
aux1->esq = aux1->dir = (struct no*) NULL;
 if (raiz == (struct no *) NULL)
raiz= aux1;

我假设no是一个名为 nom的成员的类,其类型是std::basic_string的某种实例化(例如std::string))。在这种情况下,no不是POD类型,为了使用它,您需要构造它。aux1不指向构造的no对象。它只是指向Malloc分配的原始内存。因此,您将使用不是有效的构造字符串对象的std::getline调用CC_9。调用malloc后,您需要构造一个对象。

aux1 = (struct no *) malloc(sizeof(struct no)+1);
new (aux1) no(/* constructor arguments here */);
...
// later, when you're done with the object
aux1->~no();
free(aux1);

或用new表达式分配对象,该表达式将处理分配和构造。

aux1 = new no(/* constructor arguments here */);
...
// later, when you're done with the object
delete aux1;