如何将数据存储到动态数组中

问题描述 投票:0回答:1

我有这个程序,要求用户输入数字,并询问用户是否要查看输入历史记录。所以我想知道我的代码是否正确。我想知道执行cin>>num[count-1]是否正确,或者是否有正确的方法来获取用户输入的数据。这是:

#include<iostream>
using namespace std;
int main(){
    const int size = 20;
    int *num = new int[size];
    char answer;
    int count = 1;
    while(true){
    cout<<"ENTER NUMBER: \n";
    cin>>num[count-1];
    cout<<"TRY AGAIN? ";
    cin>>answer;
        switch(answer){
            case 'y':
                count++;
                system("cls");
                break;
            default:

                cout<<"INPUT HISTORY: \n";
                for(int i=0;i<=count-1;i++){
                    cout<<num[i]<<endl;
                }
                count++;
        }
    }
    delete [] num;
    return 0;
}

我想知道正在执行cin >> num [count-1]`是正确的还是有正确的方法来获取用户输入的数据。

c++ dynamic-arrays
1个回答
0
投票

您的代码是C样式的代码。您有std :: arraystd :: vector可以帮助您编写更安全和整洁的代码。因为问题中的标签是动态数组,所以我建议使用std :: vector。在下面,您可以检查您的代码是否与替换代码一起使用。

#include <iostream>
#include <vector>

using namespace std;

int main() {
    //int *num = new int[size]; //normally you don't need to use new. Let the c++ manage it for you
    vector<int> num;
    char answer;

    while (true) {
          cout << "ENTER NUMBER: \n";
          num.emplace_back();         //Create a new element to vector num
          cin >> num.back();          //set this new element

          cout << "TRY AGAIN? ";
          cin >> answer;

          if (answer == 'y')
             system("cls");
          else {
            cout<<"INPUT HISTORY: \n";
            for (auto& numEle : num)    //It will interate over all elements of num
                cout<< numEle <<endl;
            //break; //Maybe you want to break the loop here
          }
    }
//    delete [] num;

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.