printf of int value returns only first character

866 views Asked by At

When I run the code below i get this output:

Podaj ilosc liczb: 12

Podaj liczbe nr. 0 : 53

Podaj liczbe nr. 1 : 24

Podaj liczbe nr. 2 : 53

Podaj liczbe nr. 3 : 24

Podaj liczbe nr. 4 : 66

Podaj liczbe nr. 5 : 99

Podaj liczbe nr. 6 : 3

Podaj liczbe nr. 7 : 0

Podaj liczbe nr. 8 : 5

Podaj liczbe nr. 9 : 2

Podaj liczbe nr. 10 : 5

Podaj liczbe nr. 11 : 2 Twoje liczby w odwrotnej kolejnosci: 2 5 2 5 0 3 9 6 2 5 2 5

#include <stdio.h>

int main(int argc, char **argv)
{

char tablo[100];
int k,i;
printf("Podaj ilosc liczb: ");
scanf("%d", &k);fflush(stdin);
for(i=0; i<k; i++){
                 printf("\nPodaj liczbe nr. %d : ", i);
                 scanf("%c", &tablo[i]);fflush(stdin);
                 }
printf("Twoje liczby w odwrotnej kolejnosci: \n");
for(i=k-1;i>=0;i--){
                    printf("%3c",tablo[i]);
                    }
                    printf("\n \n");

return 0;
}

Why? How to fix it? I just want my numbers in the reverse sequence.

3

There are 3 answers

0
Drew McGowen On BEST ANSWER

You're only scanning for single characters, not actual numbers. Instead, tablo should be an array of int (not char), and instead of using %c for scanf and printf, you should use %d.

2
Keith Thompson On

You're reading and writing individual characters, not integers. Try running your program with, say, x or * as input; it will just print the characters you gave it without trying to interpret them as decimal integers.

To read integers (interpreting the sequence "123" as the decimal number 123), use scanf("%d", ...) to read into an int object, and printf("%d", ...) to print the values -- and define tablo as an array of int rather than of char. (And don't forget to check the value returned by scanf, so you can tell whether it succeeded or failed.)

And don't use fflush(stdin). The behavior of fflush on input streams is undefined, and you don't really need it anyway. Later you might want a way to discard invalid input, but fflush isn't the answer.

0
John Bode On

The %c conversion specifier tells scanf to read a single character from the input stream; when you type "53", only the character '5' will be read. If you want to read numerical values and store them in a char data type, you need to use the %hhd conversion specifier:

scanf( "%hhd", &tablo[i] );

Note that if you want to store any value greater than 128, you'll need to use a wider data type such as int and the appropriate conversion specifier (%d for int, %hd for short, %ld for long, etc).

Don't use fflush on input streams like stdin; the behavior isn't defined, and it may not do what you intend.