C++ 不定长输入,保存进数组,并打印
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> arr;
int i;
do {
cin >> i;
arr.emplace_back(i);
} while (cin.get() != '\n');
for (auto it = arr.begin(); it != arr.end(); it++) {
cout << *it << " ";
}
cout << endl;
return 0;
}
输出
1 2 3 4 5 6 7
1 2 3 4 5 6 7
cin.get()获取输入一个字符,包含空格或换行等特殊字符,cin自动忽视空格或换行等特殊字符,cin读取一个个数字,cin.get()读取空格...以此交叉读取。
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> arr;
int i;
while (cin.get() != '\n') {
cin >> i;
arr.emplace_back(i);
}
for (auto it = arr.begin(); it != arr.end(); it++) {
cout << *it << " ";
}
cout << endl;
return 0;
}
输出
1 2 3 4 5 6 7
2 3 4 5 6 7
cin.get()读取第一个数字,cin忽视第一个空格读取第二个数字,cin.get()读取第二个空格...以此交叉读取,因此第一个数字1没被cin读取。