不能在一行中输入 (cin) 超过 10 个整数并用空格分隔到数组中吗?

Cannot input (cin) more than 10 integers in one line separated by spaces into an array?

我有一个简单的问题。 我正在尝试使用 while 循环将数字列表存储到数组中。

例如,假设数组的大小为 5。

如果我输入:1 2 3 4 5 然后回车,不会有任何问题

但是,如果数组的大小是 10 并且我输入: 1 2 3 4 5 6 7 8 9 10 然后它不起作用,然后跳过这些行。

我进行了搜索,但找不到任何答案。是不是不可能在一行中使用 cin 以空格分隔输入太长的数字列表? 我必须像 1 [enter] 2 [enter]...10 [enter] 那样做吗?

感谢任何帮助。

    int n=1,key,i; 
    int arra [n];


     cout << "Please enter the size of array (no more than 100): ";
     cin >> n;
     while (n>100)
     {
         cout << "Please enter a number no more than 100: ";
         cin >> n;
     }

     cout << "Please enter " << n << " numbers separated by a space and ended with Enter key: \n";

     for (i=0;i<n;i++) // store numbers into array

         cin >> arra[i];

     cout << "Please enter the key number that you want to find out: ";
     cin >> key;

     if (search(arra,n,key)==1)
        cout << "Yes, the key is in the array. \n";
     else
        cout << "No, the key is not in the array. \n";

数组长度应始终保持不变。 int arra[n] 将不起作用,因为 n 是一个变量。根据您的要求设置 int arra[50] 或其他内容。设置比必要的高一点是可以的。但是,如果您想要一个可以在 运行 中设置大小的数组,则需要 dynamic memory allocation。如果您对动态内存分配感兴趣,那么您必须学习 new and delete of c++。

错误是,您在获取输入之前将 n 的值分配给了数组的大小。

int n=1;
int arra[n];
//arra's size is 1

您应该在输入后分配大小。

while(n>100){
    cout <<"Enter a number less than 100\n";
    cin >> n;
}
//now declare the array
int arra[n];

所以现在,arra[] 具有用户输入的大小。

您正在为数组静态分配内存。尝试使用向量:

vector<int> arra;

并且在输入值时,只需在构建函数中使用:

int input;
cin >> input;
arra.push_back(input);

这样,您也不必将限制设置为 100,因为它会为每个新输入动态分配内存。