Using pointer arithmetic instead of array indexing

Hi all.

I'm currently working my way through a beginners book on C++. In the book there is an exercise that demonstrates the difference between using array indexing and pointer arithmetic to access the elements of an array. The purpose of the program is to reverse the case of letters within a string.

There is a mistake in the book - instead of showing two versions of the code (one for array indexing and one for pointer arithmetic) the array indexing code is shown twice.

Can someone please write the code below using pointer arithmetic so i can see how it works?

// Reverse case using array indexing.
#include <iostream>
#include <cctype>
using namespace std;

int main() {
int i;
char str[80] = "This Is A Test";
cout << "Original string: " << str << "\n";

for(i = 0; str[i]; i++) {

if(isupper(str[i]))
str[i] = tolower(str[i]);

else if(islower(str[i]))
str[i] = toupper(str[i]);

}

cout << "Inverted-case string: " << str;

return 0;

}


fyi - the book in question is 'C++ a beginner's guide by Herbert Schildt' - it is availble from http://msdn.microsoft.com/en-us/beginner/cc305129.aspx

Chapter 4 (pages 30-31) is where the error is.
Replace all occurrences of str[i] with *(str+i)
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cctype>

using namespace std;

int main()
{
	char str[80] = "This Is A Test";
	cout << "Original string: " << str << "\n";
	for (char * p = str; *p!='\0'; ++p)
	{
		if(isupper(*p)) *p = tolower(*p);
		else if(islower(*p)) *p = toupper(*p);
	}
	cout << "Inverted-case string: " << str << endl;
}
This is the description given underneath the incorrectly referenced code in the book.

"In this version, p is set to the start of str. Then, inside the while loop, the letter at p is checked and changed, and then p is incremented. The loop stops when p points to the null terminator that ends str."

i've given it a crack using other info provided in the book. The following code works...but is it what the author had i wonder?

//As above but this time using pointer arithmetic?

#include <iostream>
#include <cctype>
using namespace std;

int main() {

char str[] = "This is a test";
char *p;

cout << "Original string: " << str << "\n";

p = str;

while (*p){
if(isupper(*p)) *p = tolower(*p);
else if (islower(*p)) *p = toupper(*p);
*(p++);
}

cout << "inverted case string: " << str;

}
Thanks Danielsson - saw your post after working my own solution. However I see what you have done and it makes sense to me - so thanks. I wonder why the author changed the for loop to a while loop - both work.
I am glad that my answer was helpful.
Topic archived. No new replies allowed.