hzitoun
hzitoun

Reputation: 5832

C: Reading double from stdin using read system call

I am asking how can I read a double, int or any other type from stdin using the read system call.

What I've done so far:

long val ;
ssize_t r;
r = read(STDIN_FILENO,&val,sizeof(long));
printf("%ld\n",val);

Any idea?

Upvotes: 1

Views: 518

Answers (2)

Ed Heal
Ed Heal

Reputation: 60017

Use stdio and scanf

See http://linux.die.net/man/3/scanf

This will be easier to use that a raw read

EDIT

Read what you are initially expecting then try the others until you get a hit.

Better still redesign the user interface so that this problem does not arise

Upvotes: 0

abligh
abligh

Reputation: 25139

You are not being clear whether you want to read (a) the ASCII representation of a long, double, int or whatever (i.e. the string "0.12345", or (b) the binary representation of that value.

If you want to do (a), you need to use fscanf. See the above answer.

If you want to do (b), your code looks right to me. What is the 'bad result' you are having? Did you check for r<0, then look at errno or use perror().

I suspect the problem is you wanted to do (a), but have coded for (b).

Upvotes: 3

Related Questions