基本字元型別的轉換

2022-08-21 04:09:11 字數 2761 閱讀 3361

byte --- unsigned char

word --- unsigned short

dword --- unsigned long

一、int <---> cstring

int轉cstring:

int i=100;

cstring str="";

str.format("%d",i);

cstring轉int:

cstring str="123";

int i;

i=atoi(str);

//i=_ttoi(str);  (unicode)

二、float <---> cstring

float轉cstring:

float a=3.1415;

cstring str="";

str.format("%.2f",a); //保留小數點後兩位

cstring轉float:

先將cstring轉char*,因為atof()的引數為char*型,atof()的返回值為double型,可直接強轉為float型;

cstring str="3.1415";

float f;

f=atof(str);

//f=_tstof(str);  (unicode)

三、double <---> cstring

double轉cstring:

double d=3.1415;

cstring str="";

str.format("%.2lf",d);

cstring轉double:

cstring str="3.1415";

char* s;

s=str.getbuffer(str.getlength());

str.releasebuffer();

double d;

d=atof(s);

四、string <---> cstring

string轉cstring:

cstring str;

string s="hello";

str.format("%s",s.c_str());

cstring轉string:

cstring str="hello";

string s(str.getbuffer());

五、char* <---> cstring

char*轉cstring:

char schar="hello";

cstring str;

str.format("%s",schar);

afxmessagebox(str);

cstring轉char*:

方法一:

cstring str="hello";

char* s;

s=new char[str.getlength()+1];

strcpy(s,str);

方法二:

cstring str="hello";

char* s;

s=str.getbuffer(str.getlength());

str.releasebuffer();

六、tchar* <---> cstring

tchar*轉cstring:

tchar schar="hello";

cstring str;

str.format("%s",schar);

afxmessagebox(str);

cstring轉tchar*:

方法一:

cstring str="hello";

tchar* s=(lptstr)(lpctstr)str;

方法二:

cstring str="hello";

tchar* s;

s=new tchar[str.getlength()+1];

_tcscpy(s,str);

方法三:

cstring str="hello";

tchar* s;

s=str.getbuffer(str.getlength());

str.releasebuffer();

七、int <---> char*

int轉char*:

int i=54321;

char ch[5];

itoa(i,ch,10);  //10-十進位制,2-二進位制,8-八進位制,16-十六進製制

八、lpctstr <---> cstring

lpctstr相當於const tchar* -> const wchar* (unicode)/const char*

_t() ---將字串轉換為tchar,tchar是乙個巨集定義,當為unicode編碼時,tchar等同於wchar,否則等同於char

lpctstr轉cstring:

lpctstr a;

cstring b=a;

cstring轉lpctstr:

cstring a;

const char* b=(lpctstr)a;

九、ushort <---> cstring

ushort轉cstring:

ushort a;

cstring b;

b.format("%d",a);

十、byte* <---> cstring

cstring轉byte*:

cstring a;

byte* b=(byte*)(lpctstr)a;

string基本字元容器

使用string容器,需要標頭檔案 include,下面介紹string的幾種用法 1.建立string物件 string s 2.給string物件賦值 2.1 直接賦值 s abcdfeg 2.2用字元指標賦值 string s char ss 100 scanf s ss s ss 注意 sc...

mysql 基本字元函式

檢視當前字符集 show variables like char 單行函式 use myemployees 字元函式 select length 哈哈 獲取引數位元組個數 select concat last name,first name from employees 字串拼接 select up...

String 基本字元操作

排序比較 大小寫切換 判斷首尾字元 替換去除首尾空格 example trap int indexof int ch 返回指定字元在此字串中第一次出現處的索引。intindexof string str 返回指定子字串在此字串中第一次出現處的索引。intindexof int ch,int from...