C语言atoi()函数(字符串转整数int类型)(atol()转换为long)
生活随笔
收集整理的這篇文章主要介紹了
C语言atoi()函数(字符串转整数int类型)(atol()转换为long)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
需包含頭文件:C 標(biāo)準(zhǔn)庫(kù) - <stdlib.h>
文章目錄
- 描述
- 聲明
- 參數(shù)
- 返回值
- 實(shí)例
- 在windows VS上測(cè)試
- 20211206 用atoi轉(zhuǎn)換long,發(fā)現(xiàn)溢出了
描述
C 庫(kù)函數(shù) int atoi(const char *str) 把參數(shù) str 所指向的字符串轉(zhuǎn)換為一個(gè)整數(shù)(類(lèi)型為 int 型)。
聲明
下面是 atoi() 函數(shù)的聲明。
int atoi(const char *str)參數(shù)
- str – 要轉(zhuǎn)換為整數(shù)的字符串。
返回值
該函數(shù)返回轉(zhuǎn)換后的長(zhǎng)整數(shù),如果沒(méi)有執(zhí)行有效的轉(zhuǎn)換,則返回零。
實(shí)例
#include <stdio.h> #include <stdlib.h> #include <string.h>int main() {int val;char str[20];strcpy(str, "98993489");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);strcpy(str, "runoob.com");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);return(0); }讓我們編譯并運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:
字符串值 = 98993489, 整型值 = 98993489 字符串值 = runoob.com, 整型值 = 0在windows VS上測(cè)試
#include <stdio.h> #include <stdlib.h> #include <string.h>int main() {int val;char str[20];strcpy_s(str, "98993489");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);strcpy_s(str, "runoob.com");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);strcpy_s(str, "0");val = atoi(str);printf("字符串值 = %s, 整型值 = %d\n", str, val);return(0); } 字符串值 = 98993489, 整型值 = 98993489 字符串值 = runoob.com, 整型值 = 0 字符串值 = 0, 整型值 = 0參考文章:C 庫(kù)函數(shù) - atoi()
20211206 用atoi轉(zhuǎn)換long,發(fā)現(xiàn)溢出了
可以用atol嘛,,,,
在linux ubuntu虛擬機(jī)上:
#include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h>int main() {long msec = 0;char str[20] = "1638793844090";for (size_t i = 0; i < strlen(str); i++) { msec = msec * 10 + (str[i] - '0');}printf("%ld\n", msec);printf("%ld\n", atol(str));return(0); }運(yùn)行結(jié)果:
1638793844090 1638793844090總結(jié)
以上是生活随笔為你收集整理的C语言atoi()函数(字符串转整数int类型)(atol()转换为long)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 计算机里的dump是什么意思?(转储、转
- 下一篇: C语言预定义宏 __func__、__F