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的流,因此要谨言慎行。