简体   繁体   English

如何在 c++ 的 while 循环中继续存储用户输入

[英]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:使用std:vector保存数字,例如:

#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.一些小的修改和使用std::liststd::vector来存储值,向量将在您运行程序时动态增长并在空间不足时重新定位,列表将为每个新项目分配空间两者都在这里工作。

I also never use using namespace std although it is very common in tutorials to do.我也从不使用using namespace std ,尽管它在教程中很常见。

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.最后一个 for 循环中的语法auto const &i需要一些后来的 C++ 标准,它将为您提供对该项目的不可变引用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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