[英]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. 我问如何使用
read
系统调用从stdin
读取double,int或任何其他类型。
What I've done so far: 到目前为止我做了什么:
long val ;
ssize_t r;
r = read(STDIN_FILENO,&val,sizeof(long));
printf("%ld\n",val);
Any idea? 任何想法?
You are not being clear whether you want to read (a) the ASCII representation of a long, double, int or whatever (ie the string "0.12345", or (b) the binary representation of that value. 您不清楚是否要读取(a)long,double,int或其他的ASCII表示(即字符串“0.12345”,或(b)该值的二进制表示。
If you want to do (a), you need to use fscanf
. 如果你想做(a),你需要使用
fscanf
。 See the above answer. 见上面的答案。
If you want to do (b), your code looks right to me. 如果你想做(b),你的代码看起来正确。 What is the 'bad result' you are having?
你有什么'糟糕的结果'? Did you check for
r<0
, then look at errno
or use perror()
. 你检查了
r<0
,然后查看errno
或使用perror()
。
I suspect the problem is you wanted to do (a), but have coded for (b). 我怀疑问题是你想做(a),但编码为(b)。
Use stdio
and scanf
使用
stdio
和scanf
See http://linux.die.net/man/3/scanf 见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 最好还是重新设计用户界面,以免出现这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.