Reputation: 133
I continue to learn programming in C, and today I met a problem. In my program, a user must enter a value of time in minutes, and my program will calculate it seconds(very simple, actually). But I want to set a rule, that time cannot be negative. So I used this code:
if(a<=0)
{
printf("Time cannot be equal to, or smaller than zero, so the program will now terminate\n");
exit(EXIT_FAILURE);
}
but now, I don`t want to terminate my program, I want it to return to the state when a user has to enter a value.
I had a problem with terminating my program, but some search helped me, however I did not get any result searching how to restart my program.
This is the text of my program(I am working on Linux):
#include<stdio.h>
#include<stdlib.h>
main()
{
float a;
printf("\E[36m");
printf("This program will convert minutes to seconds");
getchar();
printf("Now enter your time in minutes(e.g. 5):");
scanf("%f", &a);
printf("As soon as you will press the Enter button you`ll get your time in seconds\n");
getchar();
getchar();
if(a<=0)
{
printf("Time cannot be equal to, or smaller than zero, so the program will now terminate\n");
printf("\E[0m");
exit(EXIT_FAILURE);
}
else
{
float b;
b=a*60;
printf("\E[36m");
printf("The result is %f seconds\n", b);
printf("Press Enter to finish\n");
getchar();
}
printf("\E[0m");
}
P.S. I don`t know how to correctly name this function, so I call it restart, maybe it has a different name?
Upvotes: 4
Views: 24650
Reputation: 3911
Both the solutions that have been posted work, but I personally like this approach better:
// ...
printf("Now enter your time in minutes(e.g. 5):");
scanf("%f", &a);
while(a <= 0){
printf("Time cannot be equal to, or smaller than zero, please enter again: ");
scanf("%f", &a);
}
I think it is more clear, and it gives the opportunity to have an error message and a regular message independent of each other.
Upvotes: 4
Reputation: 23699
You can simply use a do ... while
loop (including your program source code).
do {
/* Get user input. */
} while (a <= 0);
Or the goto
statement too to emulate a loop (discouraged with beginners).
start:
/* Get user input. */
if (a <= 0)
goto start;
Upvotes: 0
Reputation: 6545
you could try if-else where:
do
{
/* get user input*/
if (a > 0)
{
/* ... */
}
else
printf ("Time cannot be negative, please re-enter")
}while(<condition>);
*condition may be until when you want to continue.
Upvotes: 0