文章目录

  • ​​读取两个整数​​
  • ​​读取给定长度的一维数组​​
  • ​​读取不定长度的一维数组​​
  • ​​读取给定长度的二维数组​​
  • ​​读取不定长度的二维数组​​
  • ​​getline()​​
  • ​​cin.getline()​​
  • ​​参考文献​​


读取两个整数

#include<iostream> 
using namespace std;

int main()
{
int a, b;
while(cin>> a >> b)
cout << a + b << endl;
return 0;
}
1 2
3

读取给定长度的一维数组

#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main(){
int n;
cin >> n;

int a[n];
for(int i = 1; i <= n; i++){
cin >> a[i - 1];
}


for(int i = 1; i <= n; i++){
cout << *(a+i-1) << ",";
}
cout << endl;

return 0;
}
9
1 2 3 4 5 6 7 8 9
1,2,3,4,5,6,7,8,9,

读取不定长度的一维数组

#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main(){
vector<int> v;
int num;
for(int i = 0; ; i++){
cin >> num;
v.push_back(num);

if(getchar() == '\n'){
break;
}
}

cout << "v.size():" << v.size() << endl;

return 0;
}
1 2 3 4 5 6
v.size():6

读取给定长度的二维数组

#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main(){
int m, n; //指定矩阵行列数
cin >> m >> n;

int mat[m][n];

for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cin >> mat[i][j];
}
getchar(); //吞掉换行符
}

cout << "输出:" << endl;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << mat[i][j] << ",";
}
cout << endl;
}

return 0;
}
2
2
1 2 3 4 5
输出:
1,2,
3,4,

读取不定长度的二维数组

getline()

#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main(){
string s;
getline(cin, s);

cout << "s:" << s << endl;

return 0;
}
123 aaa
s:123 aaa

cin.getline()

cin.getline(字符数组名,接收长度,结束符)

#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main(){
char s[256];
cin.getline(s, 256, '\n');

cout << "s:" << s << endl;

return 0;
}
111 aaa
s:111 aaa