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;
}