Reputation: 557
I'm learning C and I don't understand the behavior of the code below:
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int buffer;
read(0, &buffer, sizeof(int));
printf("%d", buffer);
return 0;
}
Input:
1
Output:
2609
What's going on here? Shouldn't the output be 1?
Upvotes: 3
Views: 16996
Reputation: 81
I assume your are reading from stdin...
Use scanf function
int scanf(const char *format, ...);
In your code:
int main() {
int buffer;
scanf("%d", &buffer);
printf("%d", buffer);
return 0;
}
See URL: http://en.wikipedia.org/wiki/Scanf_format_string
Upvotes: 2
Reputation: 59617
You're reading a character
from the stream and trying to print it as an integer
.
Use:
printf("%c", buffer);
Upvotes: 1
Reputation: 29539
You need to read up on binary and ascii. You input ASCII into the console, and you're then converting it again to ascii.
Also, a character is only (usually) 1 byte. You're reading in 4 (assuming that's the size of an int). You have a lot of research and reading ahead of you.
Upvotes: 1
Reputation: 182769
You are confusing 1
, the decimal digit, with one, the number. You are also confusing the number one with the computers internal representation of the number one.
A person hitting the 1
key on the keyboard is not typing in the computer's internal representation for the number one. So reading that key directly into an integer variable will give garbage.
The computer internally stores 2609 as 0x31, 0x0A (assuming little-endian). When the person hits 1
and then enter, the keyboard sends an 0x31 (the ASCII code for 1
) and then an enter (0x0A).
But this is a case of garbage in, garbage out. You shouldn't pass the address of an integer to a function that doesn't expect a pointer to an integer.
Upvotes: 6