如何从键盘读取可变数量的变量? C++

How can a read a variable number of variable from the keyboard? C++

我想从键盘读取一个或两个值,第一个代表length_min,第二个代表length_max。在输入流中,我可以获得一个值,我可以使用 cin.get() 检查是否有另一个值,但是当我从键盘读取一个数字时,我必须引入另一个字符来打印正确的值。

阅读模板:

length + 'length_min' and/or 而不是 'length_max'(如果该行在 length_min 之后存在另一个数字,则读取 length_max)。

string length;
cin >> length;

int length_min, length_max;
cin >> length_min;

cin.ignore();  // there's a whitespace between length_min and length_max
char c = cin.get();

if (isdigit(c)) // I verified if there's a digit which represents the length_max
{
    ungetc(c, stdin);
    cin >> length_max;
}
else
{
    cin.ignore(); // if there's no digit go to next line in input stream 
    length_max = 0;
}

对于这些例子:

length 5 8 -> 它打印 5 8

length 5 + any character -> 它打印 5 0

我要删除那个额外的字符,但我不确定如何删除。

从控制台读取两个变量:

int variable_1;
int variable_2;
std::cin >> variable_1 >> variable_2;

如果第二个变量是可选的,最好的方法是一次读取一行,然后解析该行:

std::string text;
while (std::getline(std::cin, text))
{
  std::istringstream input(text);
  input >> variable_1;
  if (input >> variable_2)
  {
     // Do stuff with variable_2
  }
}