-1

With this code I am trying to build an array with integer values entered by the user. the variable "int selection" is an int, so if the value entered is an int, the while loop should keep going, but the value 0 seems to end it and I can't figure out why. Thank you for your help guys.

int main()
{
  //data to be entered
  int selection;

  //array size
  int const array_size = 100;

  //array
  int integers[array_size];

  //array index
  int index = 0;

  //prompt
  std::cout << "Enter integer ('x' to quit): " << std::endl;

  //get the data
  std::cin >> selection;

  //while data is int
  while (selection)
  {
    //put it in the array
    integers[index] = selection;

    //increment index
    index += 1;

    //get new data point
    std::cin >> selection;

  }

  return 0;

}
Duly Kinsky
  • 996
  • 9
  • 11

5 Answers5

2

This code won't do what the comment says that it would do:

//while data is int
while (selection)

The data will always be an int, it's not possible to store anything else in an int variable.

What the code actually does is to loop while the value is non-zero.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

Because 0 in Boolean context is interpreted as false.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Degustaf
  • 2,655
  • 2
  • 16
  • 27
0

false is interpreted as 0 in C++. Similarly, 0 is interpreted as false . Hence, when selection is 0, the loop effectively becomes:

while ( false )
{
...
}

which does not run.

On the other hand, when selection is not 0, C++ treats it as true and the loop will run.

EDIT: If you want to loop while the input is an integer, try

while (std::cin >> selection)
{
...
}
Ranald Lam
  • 496
  • 4
  • 9
0

This is how the code stands now and it works. Thank you guys for all your help

int main()
{
  //data to be entered
  int selection;

  //array size
  int const array_size = 100;

  //array
  int integers[array_size];

  //array index
  int index = 0;

  //prompt
  std::cout << "Enter integer ('x' to quit): " << std::endl;

  //while data is int
  while (std::cin >> selection)
  {
    //put it in the array
    integers[index] = selection;

    //increment index
    index += 1;

  }

  return 0;

}
Duly Kinsky
  • 996
  • 9
  • 11
0

while (selection) doesn't stop when selection is no longer an int; selection is always an int.

while (selection) stops when selection is not equal to 0.

You should instead test the result of the >> operation.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055