Program includes an "8", doesn't reverse digits in beginner's exercise (CodeBlocks)

So I'm writing a program that is supposed to take a two digit number and reverse the digits as an output.

instead, it includes an "8" in the beginning of the two digit number as output.

#include <stdio.h>

int main (void)
{
    int x, y;
    printf("Enter a two digit number: ");
    scanf("%d%d", &x, &y);
    printf("The reversal is: %d%d", y, x);

    return 0;
}

so when I run the program, it prompts for the number. if I enter "12" it will output "The reversal is: 812".

Just stumped

​

Edit: Tried it in a different IDE, the program hangs until I make another input, so if I enter "12" it goes to a new line, then if I enter a period "." it outputs "012"

13 comments · 57% upvoted · other discussions

comments

FUZxxl

The %d specifier reads a decimal number, not a decimal digit. You get an 8 because y is never actually scanned and thus its value is undefined.

To fix these issues, you can use %1d to scan a single digit.

Jouissance_juice [OP]

That worked, but this is the first time I've seen this problem come up with %d.

Anyway, thanks for your help!

[deleted]

[deleted]

FUZxxl

%d scans decimal integers as oposed to %o for octals and %x for hexadecimal integers.

which_spartacus

Are you supposed to do this a digit at a time?

​

scanf("%2d", &v);
printf("%d\n", v%10 + v / 10);
Jouissance_juice [OP]

yes, scan two digits separately and reverse them

​

which_spartacus

Well in that case, go with:

printf("%c%c", getchar(), getchar());

And just claim that the unspecified behavior will work with some compiler, probably.

F54280

That’s a pretty smart joke, sad to see you downvoted!

Jouissance_juice [OP]

I don't get the joke, is this a sarcasm sub?

which_spartacus

It's not really a joke -- the function arguments can be evaluated in any order. Therefore, they may be evaluated from last to first. In that case, it would reverse the two characters.

Oh_I_still_here

No it's just full of C programmers. I say this as a wannabe C programmer.

F54280

The funny idea is while everyone is talking about how to properly do the scanf, this solution does everything in a one liner, with the added bit that it will work on only some of the compilers. I am pretty sure that people who downvoted didn't realize that the code was, in fact, a solution to the original problem.

For a solution that should not rely on undefined behavior:

#include <stdio.h>

int main( int argc, char **argv )
{
    return argc = getchar(), printf( "%c%c\n", getchar(), argc )-3;
}
reebs12

I think scanf is only meant to handle char* as inputs:

​

https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm

Drach88

That is not the case. The link you included in fact states otherwise.