通过 Microsoft C++ 获得对 NaN 和 Inf 的有用处理
使用 gcc 编译时考虑以下测试程序
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, char* argv[])
{
double a=1,c=0;
double i = a/c; // divide by 0 yields infinity
double j = a*4.5;
double k = c/c; // 0 divide 0 yields NaN
FILE * fp = fopen("ttt.txt","wt");
fprintf(fp,"%f\t%f\t%f\t",i,j,k);
fclose(fp);
double aa,bb,cc;
fp = fopen("ttt.txt","rt");
fscanf(fp,"%lf%lf%lf",&aa,&bb,&cc);
cout<<aa<<endl<<bb<<endl<<cc<<endl;
}
(我尝试过的任何平台) 创建一个文件 ttt.txt,其内容为
Inf 4.500000 NaN
给出输出
Inf
4.5
NaN
没有什么奇怪的。在 C99 和 Matlab 等规则下的正确行为
在 Microsoft Visual Studio 2008 下编译相同的程序会给出一个文件 ttt.txt,其内容为
1.#INF00 4.500000 -1.#IND00
并给出输出
1
-9.25596e+061
-9.25596e+061
这样,Microsoft C 甚至无法读取它自己的 Inf 和 NaN 表示,更不用说标准的表示了,这是完全无用的 - 他们为什么要以这种方式实现它完全超出了我的理解。 我知道 MSVcc 不完全符合 C99 - 但是有没有人对如何说服它读取和写入这些值、编译器开关、另一个版本的 stdio.h 等有任何建议。
似乎解决这个问题的唯一方法是实现我自己的函数来替换 fscanf 和 fprintf,但这看起来确实像是重新发明轮子。我不敢相信我是第一个发现这个问题的人 - 以至于微软的 stdio 库变得毫无用处,但谷歌却没有发现任何关于这个问题的信息
Consider the following test program
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, char* argv[])
{
double a=1,c=0;
double i = a/c; // divide by 0 yields infinity
double j = a*4.5;
double k = c/c; // 0 divide 0 yields NaN
FILE * fp = fopen("ttt.txt","wt");
fprintf(fp,"%f\t%f\t%f\t",i,j,k);
fclose(fp);
double aa,bb,cc;
fp = fopen("ttt.txt","rt");
fscanf(fp,"%lf%lf%lf",&aa,&bb,&cc);
cout<<aa<<endl<<bb<<endl<<cc<<endl;
}
when compiled with gcc (any platform that I have tried)
creates a file ttt.txt with the contents
Inf 4.500000 NaN
gives the output
Inf
4.5
NaN
No surprises there. Correct behavior under the rules of C99, and things like Matlab
Compiling the same program under Microsoft Visual Studio 2008 however gives a file ttt.txt with the contents
1.#INF00 4.500000 -1.#IND00
and gives an output of
1
-9.25596e+061
-9.25596e+061
Such that Microsoft C can not even read it's own representations of Inf and NaN let alone the standard ones, which is utterly useless - any why they would implement it this way is completely beyond me.
I know that MSVcc is not completely C99 compliant - BUT Does anyone have any suggestions on how to persuade it to read and write these values, compiler switches, another version of stdio.h, anything.
It seems that the only way around this is to implement my own functions to replace fscanf and fprintf but that does seem like re-inventing the wheel. I can't believe I'm the first person to find this annoying - to the point of making Microsoft's stdio library useless, and yet Google is turning up nothing on the subject
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论