C++ 按空格键时获取用户输入

C++ 按空格键时获取用户输入,c++,input,C++,Input,我试图解决这个问题,用户必须输入一个数字n。然后在同一行输入n个数字。因此,在用户继续输入之前,我的程序需要知道这个数字n,以便程序知道在n之后保存这些输入的数字需要多大的动态数组。(所有这些都发生在一条线上是至关重要的) 我尝试了以下方法,但似乎不起作用 int r; cin >> r; //CL is a member function of a certain class CL.R = r; CL.create(r); //this is a member function

我试图解决这个问题,用户必须输入一个数字n。然后在同一行输入n个数字。因此,在用户继续输入之前,我的程序需要知道这个数字n,以便程序知道在n之后保存这些输入的数字需要多大的动态数组。(所有这些都发生在一条线上是至关重要的)

我尝试了以下方法,但似乎不起作用

int r; 
cin >> r;

//CL is a member function of a certain class
CL.R = r;
CL.create(r); //this is a member function creates the needed dynamic arrays E and F used bellow 

int u, v;
for (int j = 0; j < r; j++)
{
   cin >> u >> v;
   CL.E[j] = u;
   CL.F[j] = v;
}
intr;
cin>>r;
//CL是某个类的成员函数
CL.R=R;
CL.create(r)//这是一个成员函数,用于创建所需的动态数组E和F,如下所示
INTU,v;
对于(int j=0;j>u>>v;
CL.E[j]=u;
CL.F[j]=v;
}

您可以像往常一样在一行上完成:

#include <string>
#include <sstream>
#include <iostream>
#include <limits>

using namespace std;

int main()
{
  int *array;
  string line;
  getline(cin,line); //read the entire line
  int size;
  istringstream iss(line);
  if (!(iss >> size))
  {
    //error, user did not input a proper size
  }
  else
  {
    //be sure to check that size > 0
    array = new int[size];
    for (int count = 0 ; count < size ; count++)
    {
      //we put each input in the array
      if (!(iss >> array[count]))
      {
        //this input was not an integer, we reset the stream to a good state and ignore the input
        iss.clear();
        iss.ignore(numeric_limits<streamsize>::max(),' ');
      }
    }
    cout << "Array contains:" << endl;
    for (int i = 0 ; i < size ; i++)
    {
      cout << array[i] << ' ' << flush;
    }
    delete[] (array);
  }
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
int*数组;
弦线;
getline(cin,line);//读取整行
整数大小;
istringstream iss(线);
如果(!(iss>>尺寸))
{
//错误,用户未输入正确的大小
}
其他的
{
//确保检查大小>0
数组=新整数[大小];
对于(int count=0;count>数组[计数])
{
//此输入不是整数,我们将流重置为良好状态并忽略输入
iss.clear();
iss.ignore(数值限制::max(),“”);
}
}

你可能应该使用
std::vector
,但是这个解析解决方案对我来说很好。到底是什么不起作用?为什么你想让用户用空格而不是回车来分隔数字?我的键盘在数字键盘上有一个
enter
键。我看到
使用命名空间std
但我看不到
vector
;)如果OP想要一个带有
向量的解决方案,我很乐意提供一个,但我认为这看起来像是一个理解动态分配的练习,所以这是不允许的。