2 回答

TA貢獻1799條經驗 獲得超9個贊
首先你要了解atof的prototype:
double atof(const char *str);
和atoi一樣,函數的參數類型必須是char *,
而如果字符串里面沒有可以轉換的數字,
比如"abcd"的話,那么atof( "abcd" )將返回一個任意值。
而對于atoi,返回0
特別對于atoi,如果字符串為“0”的話,也會返回0,
所以不能判斷字符串中是否含有0。
而對于atof,在WIKI里寫到
“If the string is not a valid textual representation of a double, atof will silently fail, returning a random value”
所以更為危險。
所以不是什么值都可以轉化為你要的數據類型的,
當然在內存里都是以0,1儲存的,沒有類型這個概念,
而我們可以使用各種類型,其實是編譯器的功勞。
對于atoi和atof,
有新的函數可以替代
atoi可以用strtol替代,
而atof可以用strtod等替代
strtol比atoi安全,
具體的你可以查他們的用法,我講起來就有點復雜了

TA貢獻1816條經驗 獲得超6個贊
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
char *s; double x; int i; long l;
s = " -2309.12E-15"; /* Test of atof */
x = atof( s );
printf( "atof test: ASCII string: %s\tfloat: %e\n", s, x );
s = "7.8912654773d210"; /* Test of atof */
x = atof( s );
printf( "atof test: ASCII string: %s\tfloat: %e\n", s, x );
s = " -9885 pigs"; /* Test of atoi */
i = atoi( s );
printf( "atoi test: ASCII string: %s\t\tinteger: %d\n", s, i );
s = "98854 dollars"; /* Test of atol */
l = atol( s );
printf( "atol test: ASCII string: %s\t\tlong: %ld\n", s, l );
}
添加回答
舉報