mardi 30 juillet 2019

terminate called after throwing an instance of 'std::logicerror

I am creating a shoping list program using array,and when I compile the code and run it it throws me this error:

terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid

searched for some solution online but none helped the problem.

code:

#include<iostream>
using namespace std;

int main(){
  string inputnumber = 0;
  int allocationSize = 5;
  int elementsused = 0;
  int maximumAllocation = allocationSize;

  string *pArrayoflist = new string[allocationSize];

  cout << "enter list item :" ;
  cin >> inputnumber;

  while(inputnumber != "exit"){
    pArrayoflist[elementsused++] = inputnumber;

    if (elementsused == maximumAllocation){
      string *plargerArray = new string[maximumAllocation + allocationSize];

    for(int i = 0;i < allocationSize;i++){
      plargerArray[i] = pArrayoflist[i];
    }

    delete [] pArrayoflist;
    pArrayoflist = plargerArray;
    maximumAllocation += allocationSize;
    }

    cout << "enter list item :" ;
    cin >> inputnumber;


  }
  string response;
  cout << "press Y to show list : ";
  cin >> response;

  if (response == "y" || response == "Y" ){
    for (int i = 0 ; i < elementsused ; i++){
      cout << pArrayoflist[i] << endl;
    }
  }
    else{
      return 1;
    }
   return 0;
}

Aucun commentaire:

Enregistrer un commentaire