蓝桥杯 第一天

本文详细介绍了C++中的scanf和printf函数在数值和字符串输入输出上的使用,以及cin和cout的特点,包括格式化、效率对比和取消同步流以提高性能。还通过示例展示了如何在处理大量数据时优化输入输出操作。
摘要由CSDN通过智能技术生成

1.scanf和printf

1.1scanf的数值定义
int main()
{
    int a,b;
    scanf("%d %d",&a,&b);       //输入:2 9
    printf("%d,%d\n",a,b);      //输出:2 9
    double c,d;
    scanf("%lf,%lf",&c,&d);        //输入:3 5
    printf("%.2lf,%.3lf\n",c,d);    //输出:3.00 5.00
    return 0;

}
1.2scanf的字符串定义
int main()
{
    char c1,c2;
    scanf("%c:%c",&c1,&c2);//输入a:b
    printf("%c,%c",c1,c2);//输出a,b
    return 0;
}

注意:%s输入遇到空格或回车就会停下 

int main()
{
    char s[10];        //输入:hello    //输入:hello world
    scanf("%s",s);     //输出:hello    //输出:hello
    printf("%s",s);
    return 0;
}

可以使用正则表达式,表示只要不是回车就都进去

int main()
{
    char s[15];            
    scanf("%[^\n]",s);     //输入:hello world 
    printf("%s",s);        //输出:hello world
    return 0;
}

 scanf和printf的优势:

1.格式化输入和输出

2.效率高

类型对应标识符
int%d
double%lf
char%c
char[]%s
long long%lld

2.cin和cout

2.1C++数字类型
int main()
{
    int a,b;
    cin>>a>>b;    //输入2 3
    cout<<a<<' '<<b<<'\n';

    double c,d;
    cin >> c >> d;                //输入:2 3
    cout << c << '' << d << '\n'; //输出:2 3
    
    double e,f;
    cin>>e>>f;
    cout<<fixed<<setprecision(3)<<e<<' '<<f<<'\n';
    //输入:2 3
    //输出:2.000 3.000

    return 0;
}

以上可以发现  c++和c语言 不一样 如果要输出小数点的要使用 fixed<<setprecision(3) 定义

3.取消同步流

由于cin和cout需要自行判断变量类型等内部原因,读写效率比scanf和printf更低.

当数据量较大时,可能导致程序运行超时.

我们可以通过取消同步流来加速cin和cout,加速后效率相差无几.

int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    //其他操作不变
    int x;cin >> x;
    cout << x << '\n';
    return 0;
}

4.例题 

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 150;

int a[N]; //大小为N的int数组
int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    
    int n;cin>>n;//输入数组大小
    for(int i=1;i<=n;++i) cin >> a[i];//遍历数组输入
    for(int i=n;i>=1;--i) cout<<a[i]<<' ';
    return 0;
}
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
const int N = 150;

char s[N];
int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>s+1;
    for(int i=1;s[i];++i) cout << s[i];
    return 0;
}

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值