令人不安用C长长转换字符串 [英] Troubling converting string to long long in C

查看:161
本文介绍了令人不安用C长长转换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到麻烦环礁功能正确设置在C长长的价值。这是我的例子:

I'm having trouble getting the atoll function to properly set a long long value in c. Here is my example:

#include <stdio.h>

int main(void) {
    char s[30] = { "115" };
    long long t = atoll(s);

    printf("Value is: %lld\n", t);

    return 0;
}

这将打印:
值为:0

This prints: Value is: 0

这工作虽然:

printf("Value is: %lld\n", atoll(s));

这是怎么回事呢?

What is going on here?

推荐答案

首先,让我们来回答你的问题:

#include <stdio.h>
#include <stdlib.h>  // THIS IS WHAT YOU ARE MISSING


int main(void) {
    char s[30] = { "115" };
    long long t = atoll(s);

    printf("Value is: %lld\n", t);

    return 0;
}

那么,让我们来讨论和回答'为什么?':

对于非常旧的C程序的兼容性(pre-C89),使用功能,而不必宣布它是首只产生来自海湾合作委员会的警告,而不是一个错误(用第一个注释这里所指出的,也隐函数声明在C89允许的,因此产生一个错误是不恰当的,这是另外一个原因,为什么只产生一个警告)。 但是这样的函数的返回类型被假定是在文件stdlib.h INT (不是类型>为环礁例如),这就是为什么程序意外执行,但不会产生错误。如果您 -Wall编译你会看到:

For compatibility with very old C programs (pre-C89), using a function without having declared it first only generates a warning from GCC, not an error (As pointed out by the first comment here, also implicit function declarations are allowed in C89, therefore generating an error would not be appropriate, that is another reason to why only a warning is generated). But the return type of such a function is assumed to be int (not the type specified in stdlib.h for atoll for instance), which is why the program executes unexpectedly but does not generate an error. If you compile with -Wall you will see that:

警告:隐函数声明环礁

当他们使用 ATOF 不包括文件stdlib.h ,在这种情况下,预期这一事实大多人震惊未返回双值。

This fact mostly shocks people when they use atof without including stdlib.h, in which case the expected double value is not returned.

请注意:(作为一个问题的答案的评论之一的)这就是为什么环礁的结果可能会被截断的原因如果不包括正确的标题。

NOTE: (As an answer to one of the comments of the question) This is the reason why the results of atoll might be truncated if the correct header is not included.

这篇关于令人不安用C长长转换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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