阅读使用和QUOT ASCII码; D"代替" E"对于使用C科学记数法 [英] Reading ASCII numbers using "D" instead of "E" for scientific notation using C
问题描述
我有号码列表看起来像这样: 1.234D + 1
或 1.234D-02
。我想用C的功能 ATOF
只会忽略 D
键,只翻译尾数读取文件。
I have a list of numbers which looks like this: 1.234D+1
or 1.234D-02
. I want to read the file using C. The function atof
will merely ignore the D
and translate only the mantissa.
功能的fscanf
将不接受格式'%10.6e
,因为它期待一个ë
,而不是 D
中的指数。
The function fscanf
will not accept the format '%10.6e'
because it expects an E
instead of a D
in the exponent.
当我跑进在Python这个问题,我放弃了,并从字符串转换浮动之前仅仅使用字符串替换。 但是在C,我相信一定有另一种方式
When I ran into this problem in Python, I gave up and merely used a string substitution before converting from string to float. But in C, I am sure there must be another way.
那么,你将如何阅读使用数字文件 D
而不是电子
科学记数法?请注意,我说的不是如何读取字符串本身,而是如何将它们转换为浮动。
So, how would you read a file with numbers using D
instead of E
for scientific notation? Notice that I do not mean how to read the strings themselves, but rather how to convert them to floats.
感谢。
推荐答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char in[] = "1.234D+1 ABCD 1.234D-02 5\n";
char *cursor;
char *endp;
for ( cursor = strtok(in, " "); cursor; cursor = strtok(NULL, " ")) {
double d = strtod(cursor, &endp);
if ( *endp == 'D' ) {
*endp = 'e';
d = strtod(cursor, &endp);
}
if ( endp != cursor ) {
printf("%e\n", d);
}
}
return 0;
}
输出:
E:\> cnv
1.234000e+001
1.234000e-002
5.000000e+000
这篇关于阅读使用和QUOT ASCII码; D&QUOT;代替&QUOT; E&QUOT;对于使用C科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!