1、输入输出
在LeetCode等OJ上刷题有一段时间了,但是在牛客上做一些机试题目时经常会因为输入输出纠结很久,而很多公司的机试都是用的牛客平台,所以抽时间总结一下输入、输出,希望以后遇到这类问题可以很快解决,把时间花在具体算法实现上。
2、环境说明
我是用C/C++刷题,可以准备了一个简单的模板,<bits/stdc++.h>可以包含所有C++用的头文件,在g++5.4、clang++3.9版本下测试可用。
ios::sync_with_stdio(false); 加上这句可以取消cin,cout与stdio的同步,这样cin和cout的速度就和scanf和printf差不多了,能够方便很多。
1 #include <bits/stdc++.h> 2 using namespace std; 3 // 加速套餐 lambda表达式 4 static const auto io_sync_off = []() 5 { 6 // turn off sync 7 std::ios::sync_with_stdio(false); 8 // untie in/out streams 9 std::cin.tie(nullptr); 10 return nullptr; 11 }();
12 int main(){ 13 14 return 0; 15 }
3、直接多组同类数据
cin的输入忽略空格和回车。scanf("%c",&i)等价于i = getchar(),换行符和回车都会被读入。
cin>> 语句读取用户输入的数据时,它会在遇到换行符时停止。换行字符未被读取,而是仍保留在键盘缓冲区中。从键盘读取数据的输入语句只在键盘缓冲区为空时等待用户输入值,但现在不为空。
cin>> 输入结束条件:遇到Enter、Space、Tab键。对结束符的处理:丢弃缓冲区中使得输入结束的结束符(Enter、Space、Tab)
1、while+scanf 输入
输入:
1 5
10 20
输出:
6
30
可以这样写输入:
1 int main(){ 2 int a,b; 3 while(~scanf("%d %d", &a, &b)){ 4 printf("%d ",a+b); 5 } 6 return 0; 7 }
这里~scanf
与 scanf()!=EOF
一样。
scanf的返回值是输入值的个数
如果没有输入值就是返回-1
~scanf是按位取反,-1按位取反结果是0
while(~scanf("%d", &n))就是当没有输入的时候退出循环
2、while + cin 输入
1 int main(){ 2 int a,b; 3 while(cin >> a >> b){ 4 cout << a+b << endl; 5 } 6 return 0; 7 }
4、第一行数据组数t,接下里t行数据
1、先cin数据组数,然后for循环依次cin存储输入
1 int main(){ 2 int t; 3 cin >> t; 4 for(int i = 0; i < t; ++i){ 5 int a,b; 6 cin >> a >> b; 7 cout << a+b << endl; 8 } 9 return 0; 10 }
cin>>t
可以替换为scanf("%d", &t);
cin>>a>>b
可以替换为scanf("%d %d", &a, &b);
5、跳过特殊情况的输入,不输出
这里对于0 0的输入直接跳过
1 int main(){ 2 int a,b; 3 while(cin >> a >> b){ 4 if(!a && !b) break; 5 cout << a+b << endl; 6 } 7 return 0; 8 }
6、t行,每行n个数
输入:
2
4 1 2 3 4
5 1 2 3 4 5
输出:
10
15
1 int main(){ 2 int m,n,temp; 3 cin >> n; 4 5 for(int i = 0; i < n; ++i){ 6 int sum = 0; 7 cin >> m; 8 for(int i = 0; i < m; ++i){ 9 cin >> temp; 10 sum+=temp; 11 } 12 cout << sum << endl; 13 } 14 return 0; 15 }
7、多组,每行不定n个整数
输入:
1 2 3
4 5
0 0 0 0 0
输出:
6
9
0
把握住cin.get()读取字符且不从缓冲区中丢弃
1 int main(){ 2 int n,temp; 3 int sum = 0; 4 while(cin >> n){ 5 sum+=n; 6 if(cin.get() == ' '){ 7 cout << sum << endl; 8 sum = 0; 9 } 10 } 11 return 0; 12 }
cin.ignore() 和 cin.clear()
cin.get()
8、字符串空格隔开,无结尾空格
1 int main(){ 2 int n; 3 cin >> n; 4 vector<string> vec; 5 string temp; 6 for(int i = 0; i < n; ++i){ 7 cin >> temp; 8 vec.push_back(temp); 9 } 10 sort(vec.begin(), vec.end()); 11 for(int i=0;i<n;i++){ 12 // 为了最后不多一个空格 13 if(i<n-1) cout<<vec[i]<<" "; 14 else cout<<vec[i]; 15 } 16 return 0; 17 }
9、对于每组用例输出一行排序后的字符串,用','隔开,无结尾空格
输入:
a,c,bb
f,dddd
输出
a,bb,c
dddd,f
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 int main(){ 5 int n=0; 6 char c[100]={'