//接收输入一组长度不确定的数据,存入数组
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> input_array;
int num;
while (1) {
cin >> num;
input_array.push_back(num);
if (cin.get() == '\n') break; //读完数字读间隔符(空格、回车),遇回车结束
//if (getchar() == '\n') break;
}
int len = input_array.size();
for (int i = 0; i < len; i++) {
cout << input_array[i] << endl;
}
return 0;
}
补充
第一种:利用cin.get()
//把输入的字符串放入数组中,如果字符串中有空格,也会读进去
int main() {
char name[20];
//get将一行读入数组中,读取到换行符之前,停止读取;换行符保留在输入队列中
cin.get(name, 20);//name必须是char类型的数组,大小必须确定
cout << name << endl;
for (int i = 0; name[i] != '\0';i++) {
cout << name[i] << endl;
}
return 0;
}
第二种:利用分割函数
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
vector<int> splits(const string& str, const string& delim) {
vector<int> res;
if ("" == str) return res;
char* strs = new char[str.length() + 1];
strcpy(strs, str.c_str());
char* d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char* p = strtok(strs, d);
while (p) {
string s = p;
//char* c = s.c_str();
int x = atoi(s.c_str());
res.push_back(x);
p = strtok(NULL, d);
}
return res;
}
int main() {
string s;
getline(cin, s);
//输入数据
vector<int> vc = splits(s, " ");
return 0;
}