如何在用户输入-1在一个动态数组数结束程序?

问题描述 投票:0回答: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++
1个回答
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");}
© www.soinside.com 2019 - 2024. All rights reserved.