使用這類函數時,要先
#include <stdlib.h> 或
#include <cstdlib>
1. atof:將字串轉為倍精度浮點數
double atof ( const char * str );
ex:
char buffer[] = "2.675";
double f = atof(buffer);
2. atoi:將字串轉為整數
int atoi ( const char * str );
ex:
char buffer[] = "23";
int i = atoi(buffer);
3. atol:將字串轉為長整數
long int atol ( const char * str );
ex:
char buffer[] = "23";
long int i = atol(buffer);
4. strtod: 將字串轉為倍精度浮點數
double strtod ( const char * str, char ** endptr );
ex:
char buffer[] = "1011.113";
double a = strtod(buffer, NULL);
5. strtol:將字串視為任意進制,轉為長整數
long int strtol ( const char * str, char ** endptr, int base );
ex:
char buffer[] = "1011";
long a = strtol(buffer, NULL,2);
// 將 "1011" 視為2進制,轉完之後 a 即為 11
6. strtoul:將字串視為任意進制,轉為無號長整數
unsigned long int strtoul ( const char * str, char ** endptr, int base );
ex:
char *buffer = "1011";
unsigned long a = strtoul(buffer, NULL,2);
// 將 "1011" 視為2進制,轉完之後 a 即為 11
7. itoa: 整數轉為任意進制字串 (非標準函式)
char* itoa(int value, char* string, int radix);
ex:
char buffer[200];
int value = 234;
itoa(value, buffer, 2); // 將 234 轉為存成2進制之字串
8. ltoa:長整數轉為任意進制字串 (非標準函式)
char* ltoa(long int value, char* string, int radix);
ex:
char buffer[200];
lnt value = 234;
ltoa(value, buffer, 2); // 將 234 轉為存成2進制之字串
9. strtod, strtol, strtoul 使用技巧
若有一字串裡面有二個浮點數,以空白為分隔符號,
則可以下列方式取出
char buffer[] = "1.1 2.2";
char *pEnd ;
double d1, d2;
d1 = strtod(buffer, &pEnd);
d2 = strtod(pEnd, NULL);
若有若干浮點數,這些浮點數以空白為分隔符號,
則可使用下列技巧依序取出浮點數
char buffer[] = "1.12 2.2 3.3 4.455 5.5123";
char *pStart = buffer;
char *pEnd = NULL;
double d;
while(1){
d = strtod(pStart, &pEnd);
if(pStart==pEnd) break;
else pStart = pEnd;
printf("%lf\n", d);
}
同理, strtol, strtoul 也是相同技巧。
10. 擅用 sprintf 與 sscanf
(10.1) sscanf - 字串轉整數、無號數、浮點數..
ex1 :
char buffer[] = "-5, 10, 2.3, string";
int i;
unsigned u;
double d;
char buf2[200];
sscanf(buffer, "%d, %u, %lf, %s", &i, &u, &d, &buf2);
printf("%d, %u, %lf, %s\n", i, u, d, buf2);
ex2:
char demo[] = "1,2,3,4,5";
char *ptr = demo;
int a[5];
int i=0, INT=0;
while(sscanf(ptr, "%d,%s", &INT, ptr)==2) a[i++] = INT;
a[i] = INT;
for(i=0; i<5; i++) printf("%d ", a[i]);
(10.2) sprintf - 浮點數、整數、字串... 轉字串
ex:
int a=0;
float b = 1.2;
char demo[] = "Test";
char dest[200];
sprintf(dest, "%d %f %s", a, b, demo);
留言列表