void elevator_running()
{
int current_floor,next_floor;
char operation;
printf("\t\t\t\tWelcome to elevator simulator\n\n");
//
printf("Please enter the current floor: ");
scanf("%d",¤t_floor);
//
printf("Please enter where do u want to go 'u' for Up- 'd' for Down: ");
scanf("%s",&operation);
//
if (operation=='u')
{
printf("\t\t\t\tThe uping elevator is coming\n\n\n");
//
printf("\tPlease enter the next floor: -The current floor is:%d",current_floor);
//
scanf("%d",&next_floor);
//
if (next_floor>current_floor)
{
while(current_floor<next_floor)
{
current_floor++;
printf("Current floor is: %d\n",current_floor);
};
if(current_floor==next_floor)
printf("We have arrived :)");
}
//
elseif(next_floor<current_floor)
{
printf("The floor should be higher than the current one.....");
}
//
}
//
elseif(operation=='d')
{
printf("\t\t\t\tThe down elevator is coming\n");
}
//
else
{
printf("\t\t\t\tProgram ended rerun and choose between u for up and d for down");
}
//
}
Welcome to elevator simulator
Please enter the current floor: 7
Please enter where do u want to go 'u' for Up- 'd' for Down: u
The uping elevator is coming
Please enter the next floor: 9
The current floor is: 0
the next floor is: 9
Current floor is: 1
Current floor is: 2
Current floor is: 3
Current floor is: 4
Current floor is: 5
Current floor is: 6
Current floor is: 7
Current floor is: 8
Current floor is: 9
We have arrived :)
"%s" is for c-strings and will append a terminator character '\0', so you are accessing out of bounds (end up writting the memory where the floor number is stored)
for reading characters you need to use "%c", or better use c++ istreams that are type-safe
It's terminated when I replace the "%s" with "%c"
and my problem is that in line 9 the user should enter the current floor but in line 18 it gives me Zero for the current floor and start couting from 1 in line 24
Sorry, I didn't check the solution. "%c" will match the line break '\n' that is after the number.
You may simply ignore it, by instance scanf("%*c%c", &operation);
When you use "%s" it means to read an string. Strings in C are null-terminated.
So when you have
Please enter where do u want to go 'u' for Up- 'd' for Down: u
you have the "u\0" string. Two characters, that you intend to write in `operation', that is only one character long.
That causes undefined behaviour, in your case you write over `current_floor'