C++ / 输入输出模板

注意事项

  • cin后getline失效
    • 加上cin.ignore(); //重新清空流数据
  • isalpha() //判断是否字母
  • isdigit() //判断是否数字
  • include< cctype >

常用头文件

1
2
3
4
5
6
7
8
9
10
#include <bits/stdc++.h>
#include <bits/stdc++.h>
#include <bits/stdc++.h>

#include <limits.h> //INT_MAX的头文件

#include <iostream>
#include <sstream>
#include <unordered_map>
#include <algorithm>

单个字符输入

1
2
3
4
int a1 = 0;
cin >> a1;
string a2 = 0;
cin >> a2;

单行数据的输入

1
2
3
4
5
6
7
char arr[100];
cin.getline(arr, 10); //获取第10个字符之前,指针现在指在第10个字符那里
cout << arr << endl;

string _string; //获取整行元素
getline(cin, _string);
cout << _string << endl;
  • string 转 int / string.c_str();

  • int 转 string / to_string();

利用getline截取字符串流的数据

1,2,3,4,5,6转换为vector{1,2,3,4,5,6}

1
2
3
4
5
6
7
8
9
10
11
12
13
string s;
getline(cin, s);
stringstream ss(s);

vector<string> res;
vector<int> resTemp;
res.clear();
string temp;
while (getline(ss, temp, ','))
{
res.push_back(temp);
resTemp.push_back(stoi(temp, 0));
}

二维数组的输入

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
//二维数组的输入
//2 3
//110 100
void arry2input() {

int rows = 0;
int cols = 0;
cout << "请输入行" << endl;
cin >> rows;
cout << "请输入列" << endl;
cin >> cols;
vector<vector<int>>array;//定义二维数组
vector<int>v;
array.clear();
int temp = 0;
//在cin后面使用getline:需要忽略换行符后可以读取数据

cin.ignore();
cout << "请输入数值" << endl; //连续的 111 000 111
//char num[100];
//cin.getline(num, rows*cols);
string num;
getline(cin, num);
for (int i = 0; i < rows; i++) {
v.clear();
for (int j = 0; j < cols; j++) {
v.push_back(num[i++] - '0');
}
array.push_back(v);
}
}
文章作者: Inter
文章链接: https://zuizichuan.cn/2020/07/19/baseC/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Zichuan365' Blog