如何在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::list
或std::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;
}
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 按原样保存用户输入 - Ruby on Rails
- 如何在 c++ 中将密码和用户名保存到 .txt 文件中.如果用户尝试登录,我仍然希望能够检索它们
- 如何在c++中的while循环中保存用户输入
- 使用结构保存用户C++输入的信息
- C++在保存受用户输入影响的变量的状态时使用临时变量或类变量
- 保存“编辑控件”用户输入并在应用程序重新启动C++Visual Studio时进行恢复的有效方法
- 如何从用户输入值并保存在变量 wxDev-C++ 中
- 如何保存用户的整数输入,并返回字符串值?
- 将用户信息保存到加密文件中的程序
- 如何保存类用户传递的未知变量
- 在数组 (C++) 中保存用户的长数字
- C++编程:导航到用户文件以保存每个用户的应用程序数据
- Do C/C++指针保存用户数据
- 如何在InstallShield中使用用户定义的保存位置
- 将数据保存在用户无法访问的文件中C++?
- 如何在STL栈中保存用户定义的类型
- 我如何保存用户信息(如NSUserDefaults在obj-c)与c++
- 在sapi5 speak函数中存储保存用户输入数据的变量
- 为我的应用程序保存用户数据