c++ - 如果用户为动态数组中的数字输入-1,如何结束程序?
问题描述
我是编码新手,并试图创建一个动态数组,询问用户它的大小并要求输入。然后它应该打印。我遇到问题的部分是这些程序应该根据需要重复,或者直到它们输入 -1 作为数字。当他们输入 -1 时,我无法结束程序。
#include <iostream>
using namespace std;
int main()
{
int count;
cout << "How many values do you want to store in your array?";
cin >> count;
int *DynamicArray;
DynamicArray = new int[count];
for (int k = 0; k < count; k++)
{
cout << "Please input Values: ";
cin >> DynamicArray[k];
if (k == '-1') //This is the part i'm having trouble
{
cout << "The program has ended" << endl;
}
else
{
cout << endl;
}
}
for (int i = 0; i < count; i++)
{
cout << DynamicArray[i] << endl;
}
delete[] DynamicArray;
return 0;
system("pause");
}
//当我输入-1作为输入值时,它会继续在输出中打印它。//我需要它来结束程序。
解决方案
#include <iostream>
using namespace std;
int main()
{
int count;
cout << "How many values do you want to store in your array?";
cin >> count;
int *DynamicArray;
DynamicArray = new int[count];
for (int k = 0; k < count; k++)
{
cout << "Please input Values: ";
cin >> DynamicArray[k];
if (k == '-1') //This is the part i'm having trouble
{
if(DynamicArray[k]==-1){
delete[] DynamicArray;
cout << "The program has ended" << endl;
exit(0);
}
else
{
cout << endl;
}
}
for (int i = 0; i < count; i++)
{
cout << DynamicArray[i] << endl;
}
delete[] DynamicArray;
return 0;
system("pause");}
推荐阅读
- sql - 91/5000 如何使用 SQLServer 显示范围之间的日期并显示该范围内的记录数
- azure - Azure DevOps - 如何在部署期间使用 webpack 构建包
- mysql - 如何将一列连接到另一个表中的所有列
- javascript - 如何在reactjs中为用户名设置自动填充?
- r - 是否可以在 R 中编写一个函数来执行具有累积可变数量因子的判别分析?
- pdf - 如何以编程方式隐藏和显示 PDF 的某些部分?
- amazon-web-services - 如何在 CDK 中获取 AWS IoT 自定义端点?
- python - 如何在运行时使用类型定义具有内部类的类?
- postgresql - 如何在 plpgsql 中运行动态查询时访问 FOUND
- ruby-on-rails - 从下到上无限滚动的rails分页