ATOF和非空终止字符数组 [英] atof and non-null terminated character array

查看:235
本文介绍了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与非空终止字符数组太多的工作?如果是这样,它是如何知道在哪里停下?


解决方案

  

是否ATOF与非空终止字符数组的工作呢?


否,这不 的std :: ATOF 需要输入一个空结尾的字符串。未能满足这一precondition为未定义行为

未定义行为指的任何的可能发生,包括程序似乎很好地工作。这到底是怎么发生的事情是偶然您在数组的最后一个元素,它不能PTED为浮点数的再presentation的零件间$ P $,这是之后在内存中的一个字节,为什么你实施的std ::的ATOF 停止。但是,这件事情不能依赖。

您应该修正你的程序是这样的:

 字符C [] = {'0','5','\\ 0''。'};
// ^^^^

using namespace std;
int main(int argc, char *argv[]) {
    char c[] = {'0','.','5'};
    //char c[] = "0.5";
    float f = atof(c);
    cout << f*10;
    if(c[3] != '\0')
    {
        cout << "YES";
    }
}

OUTPUT: 5YES

Does atof work with non-null terminated character arrays too? If so, how does it know where to stop?

解决方案

Does atof work with non-null terminated character arrays too?

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和非空终止字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆