本文介绍了ATOF和非空终止字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用命名空间std;
INT主(INT ARGC,CHAR *的argv []){
炭C [] = {'0','5''。'};
//字符C [] =0.5;
浮动F = ATOF(C);
COUT<< F * 10;
如果(C [3]!='\\ 0')
{
COUT<< 是;
}
}
OUTPUT: 5YES
是否ATOF与非空终止字符数组太多的工作?如果是这样,它是如何知道在哪里停下?
解决方案
No, it doesn't. std::atof
requires a null-terminated string in input. Failing to satisfy this precondition is Undefined Behavior.
Undefined Behavior means that anything could happen, including the program seeming to work fine. What is happening here is that by chance you have a byte in memory right after the last element of your array which cannot be interpreted as part of the representation of a floating-point number, which is why your implementation of std::atof
stops. But that's something that cannot be relied upon.
You should fix your program this way:
char c[] = {'0', '.', '5', '\0'};
// ^^^^
这篇关于ATOF和非空终止字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!