如何在c++中的while循环中保存用户输入

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

本文关键字:保存 用户 输入 循环 while c++ 中的      更新时间:2023-10-16

用户将输入一个数字列表。用户应根据自己的意愿输入任意数量的数字。所有的数字都应该存储在一个变量中,我不想把它们全部加起来。

#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,尽管它在教程中很常见。

last-for-loops中的语法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;
}