简体   繁体   中英

how to keep storing users inputs in a while loop in c++

The user will enter a list of numbers. The user should enter as many numbers as the user wishes. All the numbers should be stored in a variable, I am not trying to add them all up.

#include <iostream>

using namespace std;
int main()
{
   // declare variables
   double number,listOfNumbers; 
   bool condition;

   cout << "Enter a starting number: ";
   cin >> number;

   condition = true;

   while (condition)
   {
      if(number > 0)
      {
         cout << "Enter another number (type 0 to quit): ";
         listOfNumbers = number;
         cin>>listOfNumbers;
      }
      else
      {
         condition=false; 
      }
   }
   cout << listOfNumbers;
   return 0;
}

Use a std:vector to hold the numbers, eg:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
   // declare variables
   double number;
   vector<double> listOfNumbers; 

   cout << "Enter numbers (type 0 to quit): ";
   while ((cin >> number) && (number != 0))
   {
      listOfNumbers.push_back(number);
   }

   for(number : listOfNumbers)
      cout << number << ' ';

   return 0;
}

Some small modifications and the use of a std::list or std::vector to store the values, the vector will grow dynamicly as you run the program and relocate if it runs out of space, the list will allocate space for every new item both works here.

I also never use using namespace std although it is very common in tutorials to do.

The syntax auto const &i in last for loops requires some of the later C++ standards it will give you a unmutable reference to the item.

#include <iostream>
#include <list>

int main() {
  // declare variables
  double number;
  std::list<double> listOfNumbers;
  bool condition;

  std::cout << "Enter a starting number: ";
  std::cin >> number;

  condition = true;

  while (condition) {
    if (number > 0) {
      listOfNumbers.push_back(number);
      std::cout << "Enter another number (type 0 to quit): ";
      std::cin >> number;
    } else {
      condition = false;
    }
  }

  for (auto const &i : listOfNumbers) {
    std::cout << i << std::endl;
  }
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM