Search code examples
cintstring-formattingc89

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: 0001234050

I 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)


Solution

  • A few things:

    • For a start, you're calling intVal() on prev, 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 to 0.