Moving strings in an array

I want to take one string in the array, make a copy of it in temp, move all the strings behind it up by one and place the copy in the last spot of the array

You can ignore the first two if statements, those are just dealing with bad situations. Pos represents the location of the string that is to be moved to the end.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int moveToEnd(string a[], int n, int pos)
{
	if (pos > n)
	{
		return -1;
	}
	
	if ((pos < 0)||(n < 0))
	{
		return -1;
	}
	string temp;
	temp = a[pos];

	if ((pos <= n) && (pos >= 0))
	{
		for (int i = pos; i < n; i++)
		{
			a[i] = a[i+1];
		
			if (i = n-1)
			{
				a[i] = temp;
			}
		}
		
	}
	return pos;
}

Here is what I'm using to debug:
1
2
3
4
5
6
int main()
string a[5] = {"a", "b", "c", "bat", "e"};
int n = moveToEnd (a, 5, 1); 
	cout << n << endl; 
	for (int i=0; i<5; i++) cout << a[i] << endl; 
		return 0; 

So the desired outcome is a, c, bat, e, b but unfortunately I get a, c, c, bat, b.
So the problem is that the array at i is not copying the value of the next string after the first time. Any suggestions?
On line 21, if (i = n-1) should have two equals signs.

Also, if i == n-1, then a[i+1] (on line 19) will be out of bounds.

On line 15, you don't really need to check to make sure pos is in the correct range, because you already did that with your first two if statements.
(By the way, for your first if statement, n is out of bounds as well, so it should be a >= sign rather than just >.)
Topic archived. No new replies allowed.