I was learning about batteries and while doing an exercise it occurred to me that instead of asking the user for numerical data, I should ask for text strings. The exercise calls for this to be done in a menu. The thing is that I made the corresponding code but when the user asks to show the registered data (names), all of them are shown except the first one.
Ex: If you type Daniel,Jose,Marta, when printing it shows Marta,Jose but does not show Daniel
Although this is not practical in a real environment, just out of curiosity, I would like someone to clarify my doubt.
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Nodo
{
string nombreCompleto;
struct Nodo *sgte;
};
void agregar(Nodo *&, string);
void sacar(Nodo *&, string&);
void menu();
int main() {
menu();
system("pause");
return 0;
}
void agregar(Nodo *&pila, string n)
{
Nodo *nuevo = new Nodo();
nuevo->nombreCompleto = n;
nuevo->sgte = pila;
pila = nuevo;
cout << "Se agrega " << nuevo->nombreCompleto;
}
void sacar(Nodo *&pila, string& n)
{
Nodo *aux = pila;
n = aux->nombreCompleto;
pila = aux->sgte;
delete aux;
}
void menu()
{
Nodo *pila = NULL;
string flag = "0", data;
int *opcion, n = 0;
do{
while (n <= 0 || n > 3)
{
cout << "Digite 1 para almacenar, 2 para mostrar los elementos de la pila y 3 para salir: "; cin >> n;
}opcion = &n;
switch (*opcion)
{
case 1:cout << "\nInserte un nombre "; cin >> data; agregar(pila, data); cout << "\n\n";
break;
case 2:cout<<"Los elementos de la pila son: \n\n";
while (pila != NULL)
{
sacar(pila, data);
if (pila != NULL) {
cout << data << " , ";
}
else
{
cout << "\n*FIN datos*\n\n";
}
}flag = "3";
break;
case 3:system("cls"); cout << "El proceso ha terminado.\n\n"; flag = "3";
break;
} n = 0;
} while (flag!="3");
}
The first data is not shown to you, because after the call to
sacar
, the pointerpila
points toNULL
so it does not exceedif
1 . You don't need that check:Other things to keep in mind.
<stdlib.h>
) that you don't even use. Read this thread for more details.Nodo
but you pass it to the functions as if it were the stack, that is as wrong as saying that a step is a ladder, honestly, do they seem the same to you?:nullptr
.sgte
) and full multiword identifiers (nombreCompleto
) in the same code, let alone in the same object!Applying fixes to follow the guidelines above, your code could look something like:
You can see the code working in Wandbox .