Hi! how do you get this output?

Income for the current pay period : -24
**Value must be greater than 0.0
**Try again. : 24..
**Trailing character encountered
**Try again. : 24
When it gets a value higher than 0 it ends the program

i typed the few codes for the first one but for some reasons it doesn't
seem to be running and giving me what i need?

#include<stdio.h>

main (){

double A;
char b;


printf (" Income for the current pay period         : ");
scanf ("%lf,%c",&A, &b);


while(A<0){
printf("**Value must be greater than 0.0\n");
printf("**Try again.                               : ");
scanf ("%lf", &A);}

???????????????
}

Recommended Answers

All 3 Replies

you will have to get it as a string, not a double, so that your program can check for extraneous characters, such as "...". If it passes that test then convert to double and check for negative value.

the below code will cover maximum combiantions

for ex:
..1

1..
.
\n
a.a
1..1..1.11

less than zero cases
0
.1
-12.1
-1.1
etc..

if you want to display the out put for particular combination
say,
when the number is .1,
out put "number should be greater than zero"
when 1..
out put "trailing characters not allowed"
etc..

just we need to have some if conditions inside while(1).

i hope you will understand the program, as its not that difficult.
revert back in case of any issues .

#include<stdio.h>
void validate(char *pay,int sz) {
	int len,i;
      char *p=pay; 
      // to repeatedly read the value until the correct value
	while(1){   
	 int dotcnt=0,n=0;
	 pay=p;
	 printf("Plz enter the Pay- value\n");
                __fpurge(stdin);
	 fgets(pay,sz,stdin);
	 len=strlen(pay);  
              while(*pay ) {
	
	  if( isdigit(*pay)||*pay=='.')
                  {
	      if(isdigit(*pay))
		n++;//atleast one digit should be in
	     if(*pay=='.')   
	         dotcnt++;
                   // to check the occurance of "." more than once
	 }
       	 pay++;
	}
       
        if( !(*pay) && ! isdigit(*pay) && !n || dotcnt > 1 || *p <= '0')
                 printf("number includes illegal chars\n");     
       else
	{
        	     break;
	}
        
}
}

int  main()
{
	char pay[50];
	validate(pay,50);
	printf("%s",pay);
	return 0;
}

A conversion function such as strtod can do the hard work of checking for valid characters in allowable locations in the input string (which is not entirely trivial). If the format is correct, the converted value is returned. You can then add range checking to the converted value.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.