#include <string>
#include<iostream>
using namespace std;
int main()
{
string str;
cin>>str;//cin遇到空格结束读取
cout<<str<<endl;
getline(cin,str);//使用getline函数可以获取包含空格的字符,以回车键结束
cout<<str<<endl;
return 0;
}
1.1.2 输入多个字符串
#include <string>
#include<iostream>
using namespace std;
int main()
{
string str;
while(getline(cin,str)){//遇到EOF/CTRL+Z则退出
cout<<str<<endl;
}
return 0;
}
2. 数组
2.1 数组的输入
2.1.1 输入一个定长一维数组
#include<iostream>
using namespace std;
int main() {
const int N = 5;
int A[N] = { 0 };
for (int i = 0; i < N; i++) {
cin >> A[i];
}
return 0;
}
2.1.2 输入一个不定长一维数组
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int>num;
int value;
while (cin >> value)//忽略空格,回车,Tab,遇到EOF会跳出循环
num.push_back(value);
return 0;
}
2.1.3 输入一个行数确定列数不确定的矩阵
#include<iostream>
#include<vector>
using namespace std;
const int N = 3;//行数是确定的
int main() {
vector<vector<int>>num(N);
int value;
for (int i = 0; i < N; i++) {
while (cin >> value) {
num[i].push_back(value);
if (getchar() == '\n')//遇到回车结束
break;
}
}
/*输出不定长数组*/
for (int i = 0; i < N; i++) {
vector<int>::iterator it;//使用迭代器输出不定长的vector
for (it = num[i].begin(); it != num[i].end(); it++)
cout << *it << "\t";
cout << endl;
}
return 0;
}
2.1.4 输入一个行数不确定列数确定的矩阵
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int a,b;
vector<vector<int>> vc;
while(cin >> a >> b)//cin遇到EOF/Ctrl+Z 或者非法字符就能退出循环
{
vector<int> tmp;
tmp.push_back(a);
tmp.push_back(b);
vc.push_back(tmp);
}
return 0;
}