Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm asking the user to input two values but one is an angle so it has to be between 0 and 360 degrees, is there a way to set limits on the scanf function?

What I have tried:

C
#include <stdio.h>

int main(void){
    double h, theta;
    printf("Enter a number for h, the hypothenuse: ");
    if(scanf("%lf", &h) != 1) {
        printf("I didn’t manage to read a number.\n" ) ;
        } else {
            printf("The number that you entered for h is %f .\n" , h ) ;
            }
    
     printf("Enter a number between 0 and 360 for the angle theta: ");
    if(scanf("%lf", &theta) != 1) {
        printf("I didn’t manage to read a number.\n" ) ;
        } else {
            printf("The number that you entered for angle theta is %f .\n" , theta ) ;
    }
    
    return 0;
}
Posted
Updated 15-Dec-20 3:31am
v2

Nope, you've to do it yourself. Check and validate the entered number.
 
Share this answer
 
No.

The scanf() functions don't do much in the way of parsing input. About the most you can do is tell them to read some number of digits, e.g.
C
scanf("%3d", &x);
That will read up to 3 digits from the input - stopping the scan at the first non-digit character. This means that if your user enters a number like 1234567, then the digits 4567 will be the available for the next input. What you need to do is to read the next token (whatever that might mean in your context, but usually something delimited by white space, but not always), and then validate it against expectations. That's almost always a good idea, since it can proactively protect you against malicious intent ( obligatory xkcd reference : xkcd: Exploits of a Mom[^] )

If you're tempted to write a function to read by character from stdin to validate as you go using getchar, be aware that input line buffered by default, which means that no data is sent to the program until [Enter] is pressed. You can turn line buffering off, but you'll have to check your OS documentation to find out how.

If you are on Linux, and would like to progress to a full-screen TUI app, then perhaps look into ncurses as an option
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900