Formatting input (removing leading zeros and decimal places) in C90?
#include <stdio.h>
int intVal(int x)
{
if(x < '0' || x > '9'){
return 0;
}
else{
x = x - '0';
return x;
}
}
int main(void)
{
int c, num, prev;
while((c = getchar()) != EOF){
num = (intVal(prev) * 10) + intVal(c);
prev = num;
printf("%d", num);
}
return开发者_如何学编程 0;
}
What I want to do with this program is input an arbitrary number to be read a char at a time, then format it into an int so that I can work with it (Don't want to use printf formatting) Also, I am only allowed to use getchar and printf for this assignment.
Sample Input: 0001234.5
edit Desired Output: <1234>(5) Actual Output: 0001234050I feel like I'm on the cusp of an epiphany but I've hit a roadblock, please help?
*edit I forgot to mention that the END result I am going for is to have the non-decimal numbers enclosed in <1234> and the decimal numbers in brackets (5)
A few things:
- For a start, you're calling
intVal()
onprev
, which is going to do all sorts of crazy things. - You have no handling for
'.'
. - An
int
cannot store values with fractional parts. - You're printing out the entire number on every iteration.
- You aren't initializing
prev
to0
.
Try it (without sign evaluation and error handling):
int main(void)
{
double x=0,op=0;
int c;
while((c = getchar()) != EOF && c!='\n')
if( c=='.' )
op++;
else
if( op )
x += (op/=10) * intVal(c);
else
x = x*10 + intVal(c);
printf("%f",x);
return 0;
}
Your function intVal is total wrong according to your requirement.
If you want get <1234>(5)
from 0001234.5
, the easiest way is using scanf
:
sscanf("%d.%d", &a, &b);
printf("<%d>(%d)\n", a, b);
see man scanf
精彩评论