如果用户在动态数组中输入-1,如何结束程序?

时间:2019-02-02 17:20:53

标签: c++

我是编码和尝试创建一个动态数组的新手,该数组要求用户提供其大小并要求输入。然后应打印。我遇到的问题是这些过程应根据需要重复,或者直到输入数字-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作为输入值时,它将继续在输出中打印它。 //我需要它来结束程序。

1 个答案:

答案 0 :(得分:0)

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