Skip to content
Advertisement

Read number from stdin and save as integer directly, using read() function

#include <stdio.h>
#include <unistd.h>

int main(){
    int num;
    int read_bytes = read(0,&num,sizeof(int));

    printf("read %d bytes :[%d]n",read_bytes,num);
}

when I execute this code, it returns just random integer like 724109877

Why this happend?
also glad to hear if someone tells me right way to read number from stdin and save as integer

Advertisement

Answer

You can do that by reading a line and convert it to a number later:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    size_t  nb_bytes, buffer_size = 32;
    char    *buffer = malloc(sizeof(char) * (buffer_size + 1));
    int     number;

    buffer[buffer_size] = '';
    nb_bytes = getline(&buffer, &buffer_size, stdin);
    number = atoi(buffer);

    printf("read %zu bytes :[%d]n", nb_bytes, number);

    free(buffer);
    return (0);
}

Note that nb_bytes will include the newline character, you can substract 1 to get the length of your number.

2nd solution

You can also simply use scanf, and then if you need to get the number’s length, you can compute it easily. Here’s an example:

#include <stdio.h>
#include <stdlib.h>

size_t get_number_length(int n)
{
    size_t length = n < 0 ? 1 : 0;

    if (n == 0)
        return (1);
    while (n != 0)
    {
        n /= 10;
        length++;
    }
    return (length);
}

int main()
{
    int number;

    scanf("%d", &number);
    size_t number_length = get_number_length(number);

    printf("read %zu bytes :[%d]n", number_length, number);

    return (0);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement