In this code I'm inserting element to an array using insertion algorithm.First,I insert element in an array.Then I use while loop if user enter 2, a new element will be added to the array,So user have to enter the location and the element. "length" variable is for updating the size of array
#include<iostream>
using namespace std;
int main(){
int sizee;
cout<<"how many names you want to enter:"<<endl;
cin>> sizee;
string name[sizee];
int length = sizee;
cout<<"Enter name: "<<endl;
for(int i=0;i<sizee;i++){
cin>>name[i];
}
while(true){
cout<<"Press 1 for check list"<<endl;
cout<<"Press 2 for insertion "<<endl;
cout<<"press 4 for exit"<<endl;
int choice;
cin>>choice;
if(choice==1){
for(int i= 0;i<length;i++){
cout<<name[i] <<" ";
}
cout<<""<<endl;
}
else if(choice==2){
cout<<"Please enter location(starts from 0): "<<endl;
int loc;
cin>>loc;
cout<<"Please enter name: "<<endl;
string update;
cin>>update;
length = length + 1 ;
name[length];
for(int i = length-2;i>=loc;i--){
name[i+1] = name[i];
}
name[loc] = update;
}
else if(choice==4){
break;
}
}
return 0;
}
Sample I/O:
how many names you want to enter:
2
Enter name:
James Sam
Press 1 for check list
Press 2 for insertion
press 4 for exit
2
Please enter location(starts from 0):
1
Please enter name:
Lucas
Press 1 for check list
Press 2 for insertion
press 4 for exit
1
James Lucas Sam
Press 1 for check list
Press 2 for insertion
press 4 for exit
My code is working for the first iteration. But when I again enter 2 for inserting new element a error occurs.
string name[sizee]is not valid c++, you should use astd::vectorinstead (which would also allow you to not have to ask the number of names in advance)name[length]is supposed to resize the array? It doesn't do anything