int转ascii
void itoa(long int value, char* string) {
int mod,count=0;
char temp[64];
if (value == 0) {
*string = '0';
*(string + 1) = ' ';
}
else {
while (value != 0) { //从低位到高位分解出各个字符
mod = value % 10;
cout << (char)(mod + 48) << endl;
value = (int)(value / 10);
temp[count] = (char)(mod + 48); //'0'-'9': 48-57
count++;
}
for (int i = count - 1; i >= 0; i--) { // 倒序输出
*string++ = temp[i];
}
*string = ' ';
}
}
int main(void) {
char string[64];
itoa(123456,string);
cout << string << endl;
system("pause");
return 0;
}
上述程序输出:
6
5
4
3
2
1
123456
无符号数和有符号数相加
int main(void) {
unsigned char a = -1;
char b = 44;
int c;
printf("0x%x
", a);
printf("0x%x
", b);
printf("0x%x
", a + b);
c = a + b;
cout << c << endl;
system("pause");
return 0;
}
以上程序段输出:
0xff
0x2c
0x12b
299
解释:a = -1 = 8'b1111_1111, b = 44 = 8'b0010_1100, a+b = 1_0010_1011=299
指针自加
int main(void) {
int a[] = { 1,3,5,7,11,13,15,17,19 };
int *p = a + 6;
for (int i = 0; i < 5; i++)
{
switch (i)
{
case(4): {cout << (*--p); break; }
case 3: {cout << (*p++); break; }
case 2: {cout << (*p--); break;}
case 1: {cout << (*++p); break; }
default: p--;
break;
}
}
system("pause");
return 0;
}
以上程序段输出:15151313
字符数组与字符数组的连接
void strcat(char s[], char ct[]) {
int i=0, j=0;
while (s[i] != ' ') i++;
while (ct[j] != ' ') s[i++] = ct[j++];
s[i] = ' ';
}
int main(void) {
char a[40] = "wt ";
char b[20] = "is a postgraduate";
strcat(a, b);
cout << "连接后的字符串为:" << endl;
cout << a<<endl;
system("pause");
return 0;
字符数组的复制
void strcpy1(char s[], char ct[]) {
int i = 0;
while (ct[i]) {
s[i] = ct[i];
i++;
}
s[i] = ' ';
}
void strcpy2(char s[], char ct[]) {
while (*ct) {
*s++ = *ct++;
}
*s = ' ';
}
void strcpy3(char * s, char * ct) {
while (*ct) {
*s++ = *ct++;
}
*s = ' ';
}
指针与数组相关的运算
int main(void) {
int i, fibon [10] = { 0,1,1,2,3,5,8,13,21,34 }, *pfib1, *pfib2; // fibon为指针常量,即隐含说明“int * const fibon”
pfib1 = pfib2 = fibon;
cout << "使用数组显示Fibonacci数列" << endl;
for (i = 0; i < sizeof(fibon)/sizeof(*fibon); i++) // sizeof函数返回的是总的存储,fibon一共10个整型元素,所有=40
cout << fibon[i] << ' ' << pfib1[i] <<endl; // "[]"是以指针作为操作数的,fibon[i]被编译器解释为*(fibon+1)
cout << "使用指针显示Fibonacci数列" << endl;
for (i = 0; i < 10; i++)
cout << *(fibon + i) << ' ' << *pfib2++ << endl; // *pfib2++ 表示*(pfib2++),先取值*pfib2,再将指针移到下一个元素
system("pause");
return 0;
}
使用数组显示Fibonacci数列
0 0
1 1
1 1
2 2
3 3
5 5
8 8
13 13
21 21
34 34
使用指针显示Fibonacci数列
0 0
1 1
1 1
2 2
3 3
5 5
8 8
13 13
21 21
34 34