C语言 字符串转换成int、long和double型
生活随笔
收集整理的這篇文章主要介紹了
C语言 字符串转换成int、long和double型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 128int main(void){char str[LENGTH];puts("請輸入字符串:");scanf("%s", str);printf("轉換為int型后為 %d。\n", atoi(str));printf("轉換為long型后為 %ld。\n", atol(str));printf("轉換為double型后為 %lf。\n", atof(str));return 0;
}
運行結果:
使用函數庫:#include <stdlib.h>
| atoi | int atoi(const char *nptr) | 將 nptr 指向的字符串轉換為 int 型表示 | 返回轉換后的值。結果值不能用 int 型表示時的處理未定義 |
| atol | long atol(const char *nptr) | 將 nptr 指向的字符串轉換為 long 型表示 | 返回轉換后的值。結果值不能用 long型表示時的處理未定義 |
| atof | double atof(const char *nptr) | 將 nptr 指向的字符串轉換為 double 型表示 | 返回轉換后的值。結果值不能用 double 型表示時的處理未定義 |
atoi 函數實現:
int atoi(const char *nptr){int flag = 1;int result = 0;if(nptr == NULL)return 0;while(*nptr == ' ' || *nptr == '\t')nptr++;if(*nptr == '-'){flag = -1;nptr++;}while(*nptr != '\0'){if(*nptr >= 0 && *nptr <= '9'){result = result*10 + (*nptr - '0');} else {break;}nptr++;}return result * flag; }atol 函數實現:
int atol(const char *nptr){int flag = 1;long result = 0;if(nptr == NULL)return 0;while(*nptr == ' ' || *nptr == '\t')nptr++;if(*nptr == '-'){flag = -1;nptr++;}while(*nptr != '\0'){if(*nptr >= 0 && *nptr <= '9'){result = result*10 + (*nptr - '0');} else {break;}nptr++;}return result * flag; }atof 函數實現:
#include <stdio.h> #define LENGTH 128 typedef enum{false,true} bool;double atof(const char* nptr){double result = 0.0;double d = 10.0;int count = 0;if(nptr == NULL){return 0;}while(*nptr == ' ' || *nptr == '\t'){nptr++;}bool flag = false;while(*nptr == '-'){ flag = true;nptr++;}if(!(*nptr >= '0' && *nptr <= '9')){ return result;} while(*nptr >= '0' && *nptr <= '9'){ result = result * 10 + (*nptr - '0');nptr++;}if(*nptr == '.'){ nptr++;}while(*nptr >= '0' && *nptr <= '9'){ result = result + (*nptr - '0') / d;d *= 10.0;nptr++;}result = result * (flag ? -1.0 : 1.0);if(*nptr == 'e' || *nptr == 'E'){ flag = (*++nptr == '-') ? true : false;if(*nptr == '+' || *nptr == '-'){nptr++;}while(*nptr >= '0' && *nptr <= '9'){count = count*10 + (*nptr - '0');nptr++;}if(flag == true) { while(count > 0){result = result / 10;count--;}}if(flag == false){ while(count > 0){result = result * 10;count--;}}}return result; }int main(void){char str[LENGTH];puts("請輸入字符串:");scanf("%s", str);printf("轉換為double型后為 %f。\n", atof(str));return 0; }總結
以上是生活随笔為你收集整理的C语言 字符串转换成int、long和double型的全部內容,希望文章能夠幫你解決所遇到的問題。