I'm making a program that takes in names, and lists them.
For example;
sNames[1] = "Bob";
sNames[2] = "Jim";
sNames[3] = "Kyle";
sNames[4] = "Tim";
sNames[5] = ""
So lets say I don't want Jim anymore. How could I make a function that will make him disappear? Since I'm a beginner at coding, I can code what I mean, so I'll just put pseudo code.
//Function name (string variable)
//Loop that checks for Jim's name
//Makes Jims name become Kyles (therefore "deleting" Jim)
//Makes Tim become Kyle
//Makes "" become Tim
//Close loop and function
So basically whats left over is.
sNames[1] = "Bob";
sNames[2] = "Kyle";
sNames[3] = "Tim";
sNames[4] = ""
So can anyone help me put my pseudo code into actually code?
OK the key to understanding the code below is this bit of code here.
1 2 3 4 5 6 7 8 9 10
// Move found entry into index[0]
string temp = names[index];
names[index] = names[0];
names[0] = temp;
// Move everything up in the array one position
for(int i = 1; i < size; i++)
{
names[i -1] = names[i];
}
If you notice the first chunk of code is taking the entry you have located and moving it to position 0.
This is is because when in the next piece of code if you move everything up in the array the information in position [0] is lost. This is because of the body of the for loop. Ask if you have questions. Hopefully this is what you are trying to solve.
#include <iostream>
#include <string>
usingnamespace std;
int findAndRemove(string names[], int& size)
{
string name1;
int index = 0;
bool found = false;
//User prompt
cout << "Enter name to be deleted " << endl;
cin >> name1;
//Find name
while( index < size && !found )
{
if(names[index].compare(name1)== 0)
{
found = true;
}
elseif(!found)
index++;
}
// Move found entry into index[0]
string temp = names[index];
names[index] = names[0];
names[0] = temp;
// Move everything up in the array one position
for(int i = 1; i < size; i++)
{
names[i -1] = names[i];
}
return size - 1;
}
int main()
{
string names[]= {"Bob","Jim","Kyle", "Tim"};
int size = 4;
int newSize = 0;
//To see before
for( int i = 0; i < size; i ++)
{
cout << names[i] << " " ;
}
cout << endl;
newSize = findAndRemove(names, size);
// To see array after
for( int i = 0; i < newSize; i ++)
{
cout << names[i] << " " ;
}
system("PAUSE");
return 0 ;
}