cin.get()的用法
https://blog.csdn.net/digitalkee/article/details/108895673
比赛地址
https://ac.nowcoder.com/acm/contest/5657#question
学习使用cin.get()之前的代码:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string str;
while (getline(cin, str)) {
int res = 0;
int len = str.size();
int i = 0;
while (i < len){
int a = 0;
while (i < len && str[i] != ' ') {
a = a*10 + str[i] - '0';
i++;
}
res += a;
i++;
}
cout << res << endl;
}
return 0;
}
学习使用cin.get()之后的代码
#include<iostream>
using namespace std;
int main(void) {
int res = 0;
int a = 0;
while(cin >> a) {
res += a;
if (cin.get() == '\n') {
cout << res << endl;
res = 0;
}
}
return 0;
}
没有学习cin.get()之前的代码
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main(void) {
string str;
while (getline(cin, str)) {
// string str;
vector<string> words;
int i = 0;
int len = str.size();
while (i < len) {
string sub;
while (i < len && str[i] != ' ') {
sub += str[i];
i++;
}
words.push_back(sub);
i++;
}
sort(words.begin(), words.end());
for (int i = 0; i < words.size(); i++) {
cout << words[i] << ' ';
}
cout << endl;
}
return 0;
}
学习了cin.get()之后的代码
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int main(void) {
string str;
vector<string> words;
while (cin >> str) {
words.push_back(str);
if (cin.get() == '\n') {
sort(words.begin(), words.end());
for (auto & s : words) {
cout << s << " ";
}
cout << endl;
words.clear();
}
}
return 0;
}
自己的代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main(void) {
string str;
while (getline(cin, str)) {
// string str;
vector<string> words;
int i = 0;
int len = str.size();
while (i < len) {
string sub;
while (i < len && str[i] != ',') {
sub += str[i];
i++;
}
words.push_back(sub);
i++;
}
sort(words.begin(), words.end());
for (int i = 0; i < words.size()-1; i++) {
cout << words[i] << ',';
}
cout << words.back() << endl;
}
return 0;
}
别人用 stringstream 的代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
while (cin >> s)
{
stringstream ss;
ss << s;
vector<string> words;
string word;
while (getline(ss, word, ','))
{
words.push_back(word);
}
sort(words.begin(), words.end());
for (int i = 0; i < (int)words.size() - 1; i ++)
cout << words[i] << ',';
cout << words.back() << endl;
}
return 0;
}