1. 一行输入未指定数量
输入
1 2 3 4 5
#include <bits/stdc++.h>
using namespace std;
int main() {
// 输入:1 2 3 4 5
string item;
while (cin >> item) {
cout << item << " ";
if (getchar() == '\n') break;
}
return 0;
}
输出:
1 2 3 4 5
2. 一行输入非空格分割
输入
1_2_3_4_5
#include <bits/stdc++.h>
using namespace std;
int main() {
//输入:1_2_3_4_5
string data;
getline(cin, data);
stringstream ss(data);
string item;
while (getline(ss, item, '_')) {
cout << item << ' ';
}
return 0;
}
输出:
1 2 3 4 5
3. 多行输入,指定行数列数
输入:
2 6
1 2 3 4 5 6
7 8 9 10 11 12
#include <bits/stdc++.h>
using namespace std;
int main() {
// 输入:
//2 6
//1 2 3 4 5 6
//7 8 9 10 11 12
int rows, cols;
cin >> rows >> cols;
vector<vector<int>> data(rows);
for (int i=0; i<rows; ++i) {
for (int j=0; j<cols; ++j) {
int temp;
cin >> temp;
data[i].push_back(temp);
}
}
for (int i=0; i<rows; ++i) {
for (int j=0; j<cols; ++j) {
cout << data[i][j] << " ";
}
cout << endl;
}
return 0;
}
输出:
1 2 3 4 5 6
7 8 9 10 11 12
4. 多行多列输入,列数已知,行数未知
输入示例:
1 5
10 20
输出示例:
6
30
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a,b;
vector<vector<int>> inputs;
while(cin >> a >> b) {
vector<int> temp{a, b};
inputs.push_back(temp);
}
for (auto &m : inputs) {
cout << m[0] + m[1] << endl;
}
return 0;
}
在牛客上运行通过,在本地IDE最后需要使用Ctrl+d结束程序,才可以输出结果
5. 多行输入,格式未统一
输入:
module3
module1, 10
module2, 5
module3, 10, module1, module2
解释:第一行是目标文件名,第二行开始,首先是一个文件名,后面试该文件的编译时间,再后面是该文件依赖的文件
输出:存放起来
#include <iostream>
#include <sstream>
#include <vector>
#include <unordered_map>
using namespace std;
int main() {
string line;
getline(cin, line);
string target = line;
string item;
unordered_map<string, vector<string>> depends;
unordered_map<string, int> times;
char c;
while (getline(cin, line)) {
if (line.empty()) break;
stringstream ss(line);
int i = 0;
string file;
while (getline(ss, item, ',')) {
if (i == 0) {
i = 1;
file = item;
depends[file] = vector<string>{};
}
else if (i == 1) {
i = 2;
times[file] = atoi(item.c_str());
}
else {
depends[file].push_back(item);
}
}
}
// 输出验证
cout << "depends:" << endl;
for (auto &m : depends) {
cout << m.first << " ";
for (auto &n : m.second) {
cout << n << " ";
}
cout << endl;
}
return 0;
}