首页 > 解决方案 > 如果用户为动态数组中的数字输入-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作为输入值时,它会继续在输出中打印它。//我需要它来结束程序。

标签: c++

解决方案


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

推荐阅读