【C++】学习笔记草稿版系列1(C到C++类型安全增强)

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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值