Monday, May 24, 2010

I'm trying to do a simple C program and I need to figure out how to check if a user input is an integer?

I'm doing a simple program that calculates sales tax to a purchase and displays the tax amount and the total cost. I'm using C (NOT C++) and the user will input the sale price then I am to convert that into the total sale and what the tax would be. Now I need to check the input that the user gives the program to verify that it is either a floating point or an integer. I think i need a float if they can use decimals right? Any help would be beneficial. Thank You For Your Time And Patience!!!

I'm trying to do a simple C program and I need to figure out how to check if a user input is an integer?
You can get sscanf to do much of the work for you. See below for some code I wrote to illustrate:





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;string.h%26gt;





#define MAX_STR_LEN 256





typedef enum { NONE = 0, INT, FLOAT, STRING, OTHER } DATA_TYPE;





typedef struct {


DATA_TYPE type;


union {


long i;


double f;


char s[MAX_STR_LEN];


} data;


} input_t;





int main(int argc, char *argv[])


{


char *s = argv[1];


input_t in = { NONE, { 0 } };





if (argc != 2) {


printf("\nusage: %s %26lt;n%26gt;\n",argv[0]);


exit(EXIT_FAILURE);


}


if ((strchr(s,'.') != NULL) %26amp;%26amp; (sscanf(s,"%lf",%26amp;in.data.f) == 1)) {


in.type = FLOAT;


} else if (sscanf(s,"%ld",%26amp;in.data.i) == 1) {


in.type = INT;


} else if (sscanf(s,"%s",in.data.s) == 1) {


in.type = STRING;


memcpy(in.data.s,s,sizeof(MAX_STR_LEN));


} else {


in.type = OTHER;


}





switch (in.type) {


case (INT):


printf("\nInt : %ld\n",in.data.i);


break;


case (FLOAT):


printf("\nFlt : %g\n",in.data.f);


break;


case (STRING):


printf("\nStr : %s\n",in.data.s);


break;


default:


puts("\nInvalid input");


break;


}


exit(EXIT_SUCCESS);


}
Reply:You can use float.


Float can handle int but Int cannot handle float or decimals.
Reply:well it is very simple just use float or decimal if use type only integer value then there is no such problem and you should display as it is.


No comments:

Post a Comment