c
#include <cstdio>
int x;
scanf("%d",&x);
printf("%d",x);
int s %d %i
float s %f
char s %c
char s[100] %s gets(s); 可接收空格 puts(s); 输出自带换行
c++
#include <iostream>
int a;
cin>>a;
cout<<a;
int s;
char s;
float s;
string s; getline(cin,s);//可接收空格
接收字符串时需要接收多余回车 getchar()或fflush(stdin);
#include <iostream>
using namespace std;
int main()
{
string s;
int a;
cin>>a;
// fflush(stdin);//清除缓冲区内容
getchar();//接收多余字符
getline(cin,s);
cout<<a<<endl;
cout<<s<<endl;
return 0;
}
输入n组数据
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int n;
// scanf("%d",&n); //c
cin>>n;//c++
while(n--)
{
//.....;
}
return 0;
}
多组文件输入 scanf 返回值为读出变量的个数 没有返回-1 EOF预定义=-1
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a,b;
//c++
// while(cin>>a>>b) cout<<a+b<<endl;
//c
// while(scanf("%d %d",&a,&b)!=EOF) printf("%d\n",a+b);
while(~scanf("%d %d",&a,&b)) printf("%d\n",a+b);
return 0;
}
条件作为结束标志
#include <iostream>
#include <cstdio>
using namespace std;
//输入 a b 以 0 0 结束
int main()
{
int a,b;
//c
// while(scanf("%d %d",&a,&b)&&(a||b)) cout<<a+b<<endl;
//c++
while(cin>>a>>b&&(a||b)) cout<<a+b<<endl;
return 0;
}
优化输入输出 1 用scanf与printf
2 cin,cout 解绑stdio
#include <iostream>
using namespace std;
int main()
{
//解绑stdio
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int a,b;
cin>>a>>b;
cout<<a+b<<endl;
return 0;
}
数字转化为字符接收数字更快速
#include <bits/stdc++.h>
using namespace std;
//输入挂 快读
void read(int &x)
{
char c=getchar();
x=0;
while(c<'0'||c>'9') c=getchar();
while(c>='0'&&c<='9')
{
x=x*10+c-'0';
c=getchar();
}
}
//输出挂 快写
void write(int x)
{
int num=0;
char c[15];
while(x)
{
c[++num]=(x%10)+'0';
x/=10;
}
while(num) putchar(c[num--]);
putchar('\n');
}
int main()
{
while(1)
{
int x;
read(x);
write(x);
}
return 0;
}