Sefa Taşcan Sefa Taşcan - 17 days ago 5
C Question

Print numbers until a negative number is entered

My problem is not related to

scanf();


For example: input ->
542-4Output
->
5,4,2,-4


I mean, print until negative number with negative number. It's okey until negative number, but I want to print negative number too. How can I do ? Please help me. I used
getchar()
,
isdigit()
,
int a=x-'0'


char x =getchar();
while(isdigit(x)){
int a=x-'0';
printf("%d,",a);
x=getchar();
}

Answer

isdigit(x) will not be true for '-', so you need to test for that separately.

Since you want to stop after the first negative number, you need to set a flag when you read the -, so you don't keep reading other negative numbers.

int neg = 0;
char x = getchar();
while (isdigit(x) || x == '-') {
    if (x == '-') {
        neg = 1;
    } else {
        int a = x - '0';
        if (neg) {
            a = -a;
        }
        printf("%d", a);
        if (neg) {
            break;
        }
    x = getchar();
}
Comments