秋招必备:C++ OJ技巧整理(输入输出)

1. 输入包含空格字符串并分割

例题:字符串最后一个单词的长度_牛客题霸_牛客网 (nowcoder.com)

方法1:C语言做法

#include <iostream>
#include <string> // geline
using namespace std;

int main() {
    string input;
    getline(cin, input);

    auto token = strtok(input.data(), " ");
    while(token != nullptr) {
        string word = string(token);
        cout << word << endl;
        token = strtok(nullptr, " ");
    }

    return 0;
}

方法2:C++做法

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main(){
    string str;
    getline(cin, str);
    stringstream ss;
    // 初始化,所以ss放左边,相当于把str的数据流给ss
    ss << str;

    while(ss) {
        // ss 重载了 >> 操作符,相当于把 ss 的第一个string 流给 str
        ss >> str;
    }
    
    return 0;
}

当然,这里的 ss 已经是一个io流了,因此可以直接通过getline处理。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main(){
    string str;
    getline(cin, str);
    
    stringstream ss(str);
    string token;
    
    while(getline(ss, token, ' ')) {
        
    }
        
    cout << token.size() << endl;
    
    return 0;
}

值得一提的是,这里如果直接把 cin 纳入处理,最后会得到一个包含\n的流,因此要谨言慎行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值