help with reversal array oder / swapping

This was on a test sometime ago. I wanna practice creating this but for some reason the swap did not show and not complete. I think there are some logic error with (count). How do i get this to work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#pragma once

#include <iostream>
using namespace std;

//contanst
const long BUFFER = 100;

class RChange
{
 public:
	//function that reversa the order
	void setCh();

 private:
	 //array
	 char nameCHAR[BUFFER];
	 long count;
};


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
30
31
32
33
34
35
36
37
38
39
40
41
#included <filename.h>
void RChange::setCh()
{
	cout << "Enter string: " ;
	cin.getline(nameCHAR, sizeof(nameCHAR));
	count = cin.gcount();
	
       // temporary fix not swapping as intented
	for (long i = count; i > 0; i--)
	{
		cout << nameCHAR[i - 1];
	}
	
	/***********************
        //intented to be swapping code
	for (long i = 0; i < count; i++)
	{
	char temp;
	temp = nameCHAR[i];
	nameCHAR[i] = nameCHAR[count];
	nameCHAR[count] = temp;

	}

	cout << nameCHAR;

	array wont swap and end up as blank or weird symbol was created

	***********************/

	cout << "\n";
	system("pause");
}

int main()
{
	RChange obj;
	obj.setCh();

	return 0;
}
Last edited on
nameCHAR's elements go from 0 to count-1, so nameCHAR[count] is out of range.

Also, your current swap will always switch nameCHAR[i] with the last character in nameCHAR. You want to swap nameCHAR[i] with the character that is 'i' characters from the end.

Finally, you don't want iterate through the entire array. If you do that, it will swap all the characters, then swap them right back. So, you want to stop looping at the halfway point.
The first for loop is not the loop that want to use and it didnt meet the requirement i want. So as long as I enter something the count in the first loop wont be out of range.

1
2
3
4
5
6
7
8
9
10
        for (long i = 0; i < count; i++)
	{
	 char temp;
	 temp = nameCHAR[i];
  	 nameCHAR[i] = nameCHAR[count];
         nameCHAR[count] = temp;

	}

	cout << nameCHAR;


I am not quiet sure how to stop the halfway. I saw some people use (count / 2) inside the for loop. Is this what you mean?
Consider the output of this program (which echoes your logic.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>

int main() {
    using std::swap;

    std::string text;
    getline(std::cin, text);

    std::cout << "Original text: \"" << text << "\"\n";

    for (std::size_t i = 0; i < text.size(); ++i) {
        swap(text[i], text[text.size() - i - 1]);
        std::cout << std::setw(3) << i << "  " << text << '\n';
    }
}
abc xyz
Original text: "abc xyz"
  0  zbc xya
  1  zyc xba
  2  zyx cba
  3  zyx cba
  4  zyc xba
  5  zbc xya
  6  abc xyz


What does this tell you about when to stop the loop?
Topic archived. No new replies allowed.