Simplifying

So I just wrote my code for this class and it works great, I was just wondering if there was a way I could simplify this? Just to pick up a few tips and tricks, what would you do to simplify the function?

Thanks!

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
//CSC150 Lab11
//Ian Heinze
//11/3/2015

#include <iostream>
using namespace std;


void reverse(char[]);

int main()
{

	char s[100];

	cout << "Please input your text: ";

	cin.getline(s, 100);

	cout << "Enter a line : " << s << endl;

	reverse(s);

	cout << "Reversed: " << s << endl;

	return 0;
}

void reverse(char *s) {
	char * i;
	for (i = s; *i; i++) {}
	 	char  temp;
	    while (s < i-1)
    {
	    	temp = *--i;
	        *i = *s;
	        *s++ = temp;
	}
}
Your loop at line 31 does nothing. The {} indicate an empty action. Why is it there?
Ah, just had them in the wrong spot, here is the revised version

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
42
//CSC150 Lab11
//Ian Heinze
//11/3/2015

#include <iostream>
using namespace std;


void reverse(char[]);

int main()
{

	char s[100];

	cout << "Please input your text: ";

	cin.getline(s, 100);

	cout << "Enter a line : " << s << endl;

	reverse(s);

	cout << "Reversed: " << s << endl;

	return 0;
}

void reverse(char *s) 
{
	char * i;
	for (i = s; *i; i++)
        {
	 	char  temp;
	    while (s < i-1)
    {
	    	temp = *--i;
	        *i = *s;
	        *s++ = temp;
	}
}
}

I guess what I'm asking is if there's maybe any easier way to write the function?
AbstractionAnon wrote:
Your loop at line 31 does nothing. The {} indicate an empty action. Why is it there?
ianheinze wrote:
Ah, just had them in the wrong spot, here is the revised version

The original for loop did what it was supposed to, which was position i to point to the end of string. Now, your code is wrong.

There are certainly different ways to write it, but the (first) implementation of your function is about as straightforward as you can get.

Better consistency with indentation is advised.


Oops. Missed that the OP was using it to position i.
Thanks cire

Topic archived. No new replies allowed.