C++中输入一组长度不确定的数据,如何接收

//接收输入一组长度不确定的数据,存入数组
#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;
}
  • 4
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值