簡體   English   中英

如何在 c++ 的 while 循環中繼續存儲用戶輸入

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

用戶將輸入數字列表。 用戶應根據自己的意願輸入任意數量的數字。 所有的數字都應該存儲在一個變量中,我不想把它們全部加起來。

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

使用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;
}

一些小的修改和使用std::liststd::vector來存儲值,向量將在您運行程序時動態增長並在空間不足時重新定位,列表將為每個新項目分配空間兩者都在這里工作。

我也從不使用using namespace std ,盡管它在教程中很常見。

最后一個 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