0
This program is an exercise to work with stacks, it’s all right, but when I decrease the stack size to exclude the last term it appears in the penultimate element of the vector.
#include <stdio.h>
#include <windows.h>
typedef struct viagem {
char nome[50];
char uf[2];
}v;
typedef struct pilha{
int topo;
int distancia;
int visitadas;
v cidades[10];
}p;
void empilhar (p *pilha) {
int dist;
system("cls");
pilha->topo++;
printf("Cidade destino: " );
scanf("%[^\n]s",&pilha->cidades[pilha->topo].nome );
printf("UF: " );
scanf("%s",&pilha->cidades[pilha->topo].uf );
printf("Distancia: " );
scanf("%i",&dist);
pilha->visitadas++;
pilha->distancia=pilha->distancia+dist;
}
void desempilhar (p *pilha){
pilha->topo--;
}
int main (){
p pilha;
pilha.topo=-1;
pilha.visitadas = 0;
pilha.distancia = 0;
int flag=1;
int opc;
do {
system ("cls");
if (pilha.topo == -1) {
printf("Voce esta em Maringa-Pr !");
}
else {
printf("Voce esta em %s-%s",pilha.cidades[pilha.topo].nome,pilha.cidades[pilha.topo].uf);
}
printf("\nVoce visitou %i cidades", pilha.visitadas );
printf("\nVoce percoreu %ikm\n", pilha.distancia );
printf("\n1-Avancar");
printf("\n2-Voltar");
printf("\n3-Sair");
printf("\nopcao: " );
scanf("%i%*c",&opc );
switch (opc) {
case 1:
empilhar (&pilha);
break;
case 2:
desempilhar (&pilha);
break;
case 3:
flag=0;
break;
}
} while(flag);
printf("Programa finalizado ! " );
scanf("%*i",&opc);
}
Note that to store 2 characters in a string (UF case) you need to provide space for the terminator character ' 0'. Declare char[3].
– anonimo
Perfect ! Thank you very much
– Jordão Qualho
The problem is not exactly on the stack, I explain: the stack you implemented stores only the variables
v.nome
andv.uf
, When you pop, this data is updated and the interface correctly informs which city the user is in. However, the stack does not store variablespilha.distancia
andpilha.visitadas
and as the functiondesempilhar()
does not change these values, when popping, the data remains unchanged.– user142154
@v.Santos' observation is pertinent
– zentrunix