//C++字串轉C字串
char c_stype[100];
string a_string("something");
strcpy(c_style,a_string.c_str());
//C字串轉C++字串
a_string = c_style;
a_string = static_cast(c_style); //使用static_cast
/* C字串稍快一點,但使用strcpy和strcat有超過字串範圍的風險 */
##ShowAll##
2009年9月21日 星期一
C/C++筆記-用static_cast轉換C,C++字串
C/C++筆記-strcpy和strcat超出字串範圍的風險
strcpy和strcat使用時會有超出字串範圍的風險
解法1:可用assert函式來避免
解法2:strncpy(name,"Oualline",sizeof(name)-1);
最後一個會自動補'\0'
解法2:strncat(name,"Oualline",sizeof(name)-strlen(name)-1);
若空間已滿,則'\0'就不會自動加入,需自行填入,
多寫一行程式碼 name[sizeof(name)-1]='\0';
加上此行程式碼若未超出空間會多一個'\0',但不影響
解法1:可用assert函式來避免
解法2:strncpy(name,"Oualline",sizeof(name)-1);
最後一個會自動補'\0'
解法2:strncat(name,"Oualline",sizeof(name)-strlen(name)-1);
若空間已滿,則'\0'就不會自動加入,需自行填入,
多寫一行程式碼 name[sizeof(name)-1]='\0';
加上此行程式碼若未超出空間會多一個'\0',但不影響
2009年9月19日 星期六
2009年9月12日 星期六
C/C++筆記-代表null的字元
char name[6];
name[0] = 'J';
name[1] = 'a';
name[2] = '\0';
name[3] = 'e';
name[4] = 's';
name[5] = 'm';
printf("%s",name);
畫面只會輸出Ja,讀到'\0'會認定字串已結束
##ShowAll##
C/C++筆記-strcpy複製字串
//連同'\0',from字串複製到to字串
strcpy(char *to, const char *from)
strncpy(char *to, const char *from, size_t len)
C/C++筆記-strcat連結字串
//str1之後接str2
strcat(char *str1, const char *str2)
strncat(char *str1, const char *str2, size_t len)
C/C++筆記-strcmp比較字串
strcmp(const char *str1, const char *str2)
strncmp(const char *str1, const char *str2, size_t len)
/* 相等傳回0,小於傳回負數,大於傳回正數 */
訂閱:
文章
(
Atom
)