C++ doesn’t like type transformation and point.
//C++
char *p = (char *)malloc(100); // malloc -> void*
C uses 0 and 1 to demonstrate false and true.
C doesn’t have string type and boolean type, while C++ has.
C++ doesn’t needs typedef.
//C++
enum BOOL
{
FALSE, TRUE
};
BOOL m = False;
Real enumeration.
The enumeration in C does not reach its reputation.
//C
enum DAY
{
Mon, Tue, Wed
};
int main()
{
enum Day today;
today = 100;
return 0;
}
The compiler will not report any error in C.
However, it will report error in C++, which means real enumeration.
枚举当作宏使用
C++尽量不要用宏,能用const和枚举代替的尽量用这两个代替。
enum
{
spr = 0, sum, autu, win
};
//C
int main()
{
int a, b = 10;
a = b = 100;
// first 100->b
// b -> a
(a = b) = 100;// ERROR, 表达式可以赋值但是不可以被赋值
}
int main()
{
int a, b;
int c = (a = 10) + (b = 40) \\ c= 50
}
//C++
int main()
{
int a, b = 5;
a = b = 100; // a = 100, b = 100
a = 5; b = 5;
(a = b) = 100; // b -> a 100 -> a
// 表达式可以被赋值,运算符重载
a = 5; b = 5;
(a!=b?a:b) = 1000; // a = 1000, b = 5
}
cin cout 类对象, 具有和scanf和sprinf(函数)相同的功能
//C++
int main()
{
char name[30];
//scanf("%s", name); //不安全
cin>>name;//流输入运算符(重载,一词多义,决定于语境),不安全
printf("name = %s\n", name);
}
string a;
cout<<a.max_size()<<endl;
cin>>a; // 安全,你有多大脚,我有多大鞋
int a; int b;
cin >>a>>b; // cin>>a; cin>>b; 仅表示先后顺序
cout<<a<<b<<endl;
cin, cout 格式问题
设定宽度
# include <iostream>
# include <iomanip>
int main()
{
int a = 12345; float b = 1234.567;
cout<<setw(8)<<a<<endl;
return 0;
}
设定对齐格式
# include <iostream>
# include <iomanip>
int main()
{
int a = 12345; float b = 1234.567;
cout<<setiosflags(ios::left)<<setw(8)<<a<<endl;//设置左对齐
return 0;
}
实现给定小数位和有效数字
# include <iostream>
# include <iomanip>
int main()
{
int a = 12345; float b = 1234.567;
cout<<setprecision(2)<<setiosflags(ios::fixed)<<setw(8)<<b<<endl;
return 0;
}
进制
# include <iostream>
# include <iomanip>
int main()
{
int a = 12345; float b = 1234.567;
printf("%x\n", a);
printf("%o\n", a);
printf("%d\n", a);
cout<<hex<<a<<endl;
cout<<oct<<a<<endl;
cout<<hex<<a<endl
return 0;
}
设置填充符
cout<<setfill('x')<<setw(10)<<a<<endl;
cout<<setfill('x')<<setiosflags(ios::left)<<setw(10)<<a<<endl;