c++几种解决输入输出的方法——常见类型和strtok()方法

总结一下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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值