C++对C的扩展之cin与cout

一、cin

 

//C++语言

 

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string>

using namespace std;


int main(){
//    char name[30];
//    scanf("%s", name);  //不安全
//    printf("name = %s\n", name);
//    gets(name);  //不安全
//    printf("name = %s\n", name);
//    fgets(name, 30, stdin);  //安全,但只读取输入的29个字符,第30个字符是'\0'
//    printf("name = %s\n", name);

 

//    cin >> name;    //不安全

//    cout << name << endl;

string name;

cin >> name;

 

    cout << name << endl;

 

}

 

C++中的cin, cout 均是类对象,C中的scanf和printf均是函数。

其中scanf, gets, fgets ,包括cin均是不安全的, 当输入大于29个字符时,全部运行时出错,其重点在于char name[30];的定义是不安全的,使用string类型(C++新增类型,C中没有string), string是个类, 是非常强大,也是足够安全的,最多能够存储1073741820个字符(通过name.max_size()可查看),几乎可以说是绝对安全的。

 

二、cout

 

//C++语言
#include<iostream>
#include<iomanip>
#include<stdio.h>


using namespace std;


int main(){
    int a = 12345;
    float b = 1234.567;
    printf("--------c---------\n");
    printf("%d\n", a);   //12345
    printf("%8d\n", a);                                                                          //   12345(右对齐,三个空格填充)
    printf("%-8d\n", a);                                                                        //12345   (左对齐,三个空格填充)
    printf("%f\n", b);                                                                             //1234.567017(浮点型默认输出6位小数)
    printf("%.2f\n", b);    //1234.57 (保留两位小数)
    printf("%10.2f\n", b);   //   1234.57(10位有效数字,左边三个空格填充,保留两位小数)


    cout << "------c++----------" << endl;
    cout << a <<endl;   //12345
    cout << setw(8) << a << endl;   //   12345(右对齐,左边三个空格)
    cout << setiosflags(ios::left) << setw(8) << endl;     //12345   (左对齐,右边三个空格)
    cout << setfill('x') << setw(8) << a << endl;    //xxx12345
    cout << b << endl;   //1234.57(c++默认6位有效数字)
    cout << setprecision(3) << setiosflags(ios::fixed) << b <<endl;   //1234.567
    cout << setw(10) << setprecision(3)  << setiosflags(ios::fixed) << b << endl; //  1234.567(右对齐,左边里两个空格填充)
}

注意:以上代码不存在前后逻辑关系,当成单句输出,忽略前后干扰现象

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值