I have written a code which checks when scanf() returns a negative number, for example if I press "Ctrl+Z" it should get out of the while loop and printf("Finish!") , but instead it is not printing the "finish!" can anybody take a look?
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define G 9.81
float Height(float speed, float angle, float time);
float Horizontal(float speed, float angle, float time);
void main()
{
float speed;
float angle;
float time = 0.1;
float height = 0;
float horizontal = 0;
int res = 0;
printf("Enter v <0.0 - 100.0 m/s> and a <0-90 degrees>: ");
res = scanf_s("%f %f", &speed, &angle);
while (res != -1)
{
for (time = 0.1; height >= 0; time += 0.1)
{
printf("Time: %.1f .... H = %.2f S = %.2f \n", time, horizontal = Horizontal(speed, angle, time), height = Height(speed, angle, time));
}
height = 0;
printf("Fallen!\n");
printf("Enter v <0.0 - 100.0 m/s> and a <0-90 degrees>: ");
res = scanf_s("%f %f", &speed, &angle);
}
printf("\nFinish!\n");
getch();
}
float Height(float speed, float angle, float time)
{
float height;
angle = ((3.14 / 180) * angle);
height = (speed * sin(angle) * time) - ((G*time*time) / 2);
return height;
}
float Horizontal(float speed, float angle, float time)
{
float horizontal;
angle = ((3.14 / 180) * angle);
horizontal = (speed * cos(angle)) * time;
return horizontal;
}
I'm using Visual Studio (C language) on Windows.
scanf
in your question, but your code usesscanf_s
, which is not a standard function (I think it's a Microsoft thing?). I think you're also assuming thatEOF
is -1, which is not guaranteed to be true in general (though it may be in the MS case, I don't know and don't have a compiler handy to check!). Thescanf
function returns the number of fields assigned - not characters written - orEOF
on error, or if when reading the first character it gets end-of-file. I think to force an end-of-file condition you have to press Enter-Ctrl+Z-Enter, so that might be the issue? – psmears