总结一下acm中几种常见的c++处理输入输出的方法
(一)计算a+b
//输入
1 2
4 5
//输出
3
9
#include<bits/stdc++.h>
using namespace std;
int main(){
int a, b;
while(cin>>a>>b){
cout<<a+b<<endl;;
}
return 0;
}
(二)计算一系列数的和
//输入
1 2 3
4 5
0 0 0 0 0
//输出
6
9
0
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<vector<int>>inputs;
string buffer;
while(getline(cin, buffer)){
vector<int>line;
char* split = strtok((char*) buffer.c_str(), " ");
while(split != NULL){
line.push_back(stoi(split));
split = strtok(NULL, " ");
}
inputs.push_back(line);
}
for(int i=0; i!=int(inputs.size()); ++i){
int sum = 0;
for(int j=0; j!=int(inputs[i].size()); ++j){
sum += inputs[i][j];
}
cout<<sum<<endl;
}
return 0;
}
(三)对输入的字符串进行排序后输出
//输入
a c bb
f dddd
nowcoder
//输出
a bb c
dddd f
nowcoder
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<vector<string>>inputs;
string buffer;
while(getline(cin, buffer)){
vector<string>line;
char* split = strtok((char*) buffer.c_str(), " ");
while(split != NULL){
line.push_back(split);
split = strtok(NULL, " ");
}
inputs.push_back(line);
}
for(int i=0; i!=int(inputs.size()); ++i){
sort(inputs[i].begin(), inputs[i].end());
for(int j=0; j!=int(inputs[i].size()); ++j){
cout<<inputs[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
(四)对输入的字符串进行排序后输出(字符串用逗号隔开)
//输入
a,c,bb
f,dddd
nowcoder
//输出
a,bb,c
dddd,f
nowcoder
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<vector<string>>inputs;
string buffer;
while(getline(cin, buffer)){
vector<string>line;
char* split = strtok((char*) buffer.c_str(), ",");
while(split){
line.push_back(split);
split = strtok(NULL, ",");
}
inputs.push_back(line);
}
for(int i=0; i!=int(inputs.size()); ++i){
sort(inputs[i].begin(), inputs[i].end());
if(inputs[i].empty()) continue;
cout<<inputs[i][0];
for(int j=1; j<int(inputs[i].size()); ++j){
cout<<","<<inputs[i][j];
}
cout<<endl;
}
return 0;
}