ACM输入模式

基本知识

  • 包含所有C++头文件的方式;
1
#include <bits/stdc++.h>
  • cin读取的每个数据以空格和回车分隔;
  • cin >> var会自动将输入流中数据转换为var类型;
  • cin>>输入的数据不包含空格和回车,空格和回车会存入到cin的缓冲区中;
  • cin是丢弃回车的,如果想拿到输入的空格和回车,通过cin.get()获得;
  • cin.get()不是当前cin的内容,而是下一个内容;
  • cin.get()是保留回车在输入流队列中的,可以读取每个字符,包括空格和回车;
  • 使用while(cin >> var)读取时,在while循环中,cin只有在遇到文件结束符EOF,或无效输入时退出;

模板一

不提示输入组数,根据回车符判断一组数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <bits/stdc++.h>

using namespace std;

class Solution {
private:
long sum = 0;
public:
bool input() {
long a = 0;
while (cin >> a) {
sum += a;
if (cin.get() == '\n') return true;
}
return false;
}
void output() {
cout << sum << endl;
}
void run() {
while (input()) {
output();
sum = 0;
}
}
};

int main() {
auto ptr = make_unique<Solution>();
ptr->run();
return 0;
}

模板二

读取单个字符要用cin.get();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <bits/stdc++.h>

using namespace std;

class Solution {
private:
vector<string> vs;
public:
bool input() {
string s;
char ch;
// 读取字符用cin.get(ch), 不能是cin >> ch
while (cin.get(ch)) {
if (ch == ',' || ch == '\n') {
vs.push_back(s);
s.clear();
if (ch == '\n') return true;
} else {
s += ch;
}
}
return false;
}

void output() {
cout << vs[0];
for (int i = 1; i < vs.size(); ++i) {
cout << "," << vs[i];
}
cout << endl;
}

void run() {
while (input()) {
sort(vs.begin(), vs.end());
output();
vs.clear();
}
}
};

int main() {
auto ptr = make_unique<Solution>();
ptr->run();
return 0;
}

模板三

借助stringstream;

1
2
3
4
5
6
7
8
9
10
11
bool input() {
string line;
// 直接读取一行,包括换行符
if (getline(cin, line)) {
stringstream ss(line);
string str;
while (ss >> str) vs.push_back(str);
return true;
}
return false;
}

模板四

借助getline分割

1
2
3
4
5
6
7
8
9
10
11
12
bool input() {
string line;
// 直接读取一行,包括换行符
if (getline(cin, line)) {
stringstream ss(line);
string str;
// 从逗号分割
while (getline(ss, str, ',')) vs.push_back(str);
return true;
}
return false;
}

ACM输入模式
http://example.com/2022/08/02/ACM输入模式/
作者
ZYUE
发布于
2022年8月2日
更新于
2022年8月2日
许可协议