C++请教,通过键盘输入一串未知长度的数字初始化一个数组进行操作!!!

我想达到的目的是:用户可以通过控制台界面输入任意个(不超过1024)整形数,程序进行排序。但是我的排序是通过将各个数编入数组中进行实现,但是这样的话,总要提前让人输入总的个数,我才能初始化这个数组,确定有用的数组范围。
怎么能不让用户自己输入要比较的数字的个数呢?
我能想到的办法就是如下解决的:
cout<<"请输入所要排序的数的个数:"<<endl;
int n;cin>>n;
int numbers[1024]={-1};
cout<<"请输入数列,以enter键结束"<<endl;
for(int i=0;i<n;i++)
cin>>numbers[i];
cout<<endl;
sort(numbers,n);
请教高人指点能否没有预先告知大小这一步?(C++语言)

排序时数组的长度肯定是不能缺少的,可以采用下面的方式实现数组的不定长输入:

int n = 0;
int numbers[1024]={-1};
while(cin)
{
cin>>number[n];
n++;
}

这样就可以了,输入任意一个字符终止输入
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-12-14
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
vector<int> a;
while (1) {
int x;
cin >> x;
if (x == -1) break;
a.push_back(x);
}
sort(a.begin(), a.end());
}
以-1为结尾
相似回答