0

我正在尝试解决用户必须输入数字 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;
}
4

1 回答 1

2

您可以像往常一样在一行上执行此操作:

#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);
  }
}

这里是演示,你可以看到输入是一行6 1 2 3 4 5 6

再一次,我没有检查所有内容,因此请按照您的需要进行处理。

编辑:在读取错误后添加了流的重置。

于 2013-06-05T17:27:41.597 回答