c - How to make getchar() read a negative number? -


i writing program can calculate areas of square, cube, , circle. program needs present error message , allow user enter new choice if enter not included in menu. problem if type includes menu options program still executes. (i.e. -1, 23, 344) wondering how ignore after first character or read whole string. or if there better getchar(). i'm open solutions! thank you!

#include <stdio.h> #include <stdlib.h>  int main(void) {  int choice; int lengthsq; int areasq; int lengthcube; int areacube; int radius; double circlearea;  printf("area calculation\n"); printf("(1) square\n"); printf("(2) cube\n"); printf("(3) circle\n"); fputs("please make selction: ", stdout);  while((choice = getchar()) != '\n')  switch (choice) {    case '1':     printf("\nplease enter length: ");       scanf("%d", &lengthsq);       while(lengthsq <= 0){         printf("error! please enter positive number: ");           scanf("%d", &lengthsq);       }     areasq = lengthsq * lengthsq;     printf("the area of square %d.", areasq);     return 0;    case '2':     printf("\nplease enter length: ");       scanf("%d", &lengthcube);       while (lengthcube <= 0) {         printf("error! please enter positive number: ");           scanf("%d", &lengthcube);       }     areacube = 6 * lengthcube * lengthcube;     printf("the surface area of cube %d.\n", areacube);     return 0;    case '3':     printf("\nplease enter radius: ");       scanf("%d", &radius);       while(radius <= 0){         printf("error! pleae enter postive number: ");           scanf("%d", &radius);       }     circlearea = 3.14159 * radius * radius;     printf("the area of circle %.2f.\n", circlearea);     return 0;    case '\n':   case '\t':   case ' ':     break;    default:     printf("\ninvalid choice entered.\n");     fputs("enter new choice: ", stdout);     break;  }  } 

you add switch case dash, toggle kind of negative flag , read number you're doing. if not introducing such flag, best option using fgets, returns entire input line. has downside need parse input. i.e. string manipulation, may more complex simple flag parameter.

on other hand, code attached, deduct valid input consists of mere numbers (integers). read integer scanf.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -