# C++、Python中输入读取API

### 1. 读入数值

#include <iostream>
#include <vector>
using namespace std;
void print_arr(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout<< arr[i]<<" ";
cout << endl;
}
void print_double_arr(int **arr, int n)
{
for (int i = 0; i < n / 2; i++)
{
for (int j = 0; j < 2; j++)
cout << arr[i][j] << " ";
cout << endl;
}
}
void print_vector(vector<int> vec)
{
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
cout << endl;
}
int main()
{
//读取一行指定长度的数值保存到一维数组中
int n;
cin >> n;
int *arr = new int[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
print_arr(arr, n);

//读取一行指定长度的数值保存到vector中
vector<int> vec;
int n,data;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> data;
vec.push_back(data);
}
print_vector(vec);

//读取一行指定长度的数值保存到二维数组中
int n;
cin >> n;
int **arr = new int*[n / 2];
for (int i = 0; i < n / 2; i++)
arr[i] = new int[2];
for (int i = 0; i < n / 2; i++)
for (int j = 0; j < 2; j++)
cin >> arr[i][j];
print_double_arr(arr, n);

return 0;
}

### 2. 读入字符

1. cin.get(arr, 10)和cin.getline(arr,10)

#include <iostream>
#include <string>
using namespace std;
int main()
{
//读入一个字符
char a;
a = getchar();
cout << a;

//读取一行字符到指定长度的数组中
char arr[10] = {NULL};
cin.getline(arr, 10);
cout << arr << endl;

//读取指定结束字符的字符到指定长度的数组中
char arr[10] = { NULL };
cin.getline(arr, 10, '\t');
cout << arr << endl;

//读取一行字符，而不需指定数组长度
string str;
getline(cin,str);
cout << str << endl;

return 0;
}

### Python部分

python2
input()函数

raw_input()函数

python3
input()函数

# 输入为一个数字
num = input("num = ")
print("num = ",num,type(num))

# 输入为两个数字
num = input("num = ")
print("num = ",num)
# 指定字符分割字符串，并将其转化为整型类型
num = num.split(' ')
num = [int(i) for i in num]
print("num = ",num)

# 指定行数，输入多行数字
num = input("num = ")
arr = []
for i in range(int(num)):
line = input()
line = line.split(' ')
line = [int(i) for i in line]
arr.append(line)
print("arr = ", arr)

# 输入字符串
str = input("str = ")
print("str = ",str,type(str))

# 二维数组按指定列排序
arr = [[4,2],[1,3]]
arr.sort(key=lambda x: x[0])
print(arr)