pointers testing

Apr 10, 2011 at 5:38pm
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
#include<iostream>
#include<cstring>
using namespace std;



int main(void) 
{




	char* name = "Charmander";  
	cout << "The name is " << name << ".\n";
	cout << "Part of the name is " << name+3 << ".\n";
	// but we can still output a single char using the pointer
	cout << "The fourth letter in name is " << *(name+3) << ".\n";
	name = "Charmeleon"; // so we don't need strcpy . . . 
	cout << "The (evolved) name is " << name << ".\n";
	char* name2 = "Charizard";
	name = name2;  // char pointers CAN be reassigned . . . 
	cout << "The NEW evolved name is " << name << ".\n";
	name = "Dark Charizard";
	cout << "Name2 is " << name2 << ".\n";
	cout << "Name is " << name << ".\n";
	// Robert's experiment - advance pointer past end of string
	cout << "name+33 = " << name+33 << endl;
	cout << "*(name+33) = " << *(name+33) << endl;

}


as you can i see i went through the tutorial and i know how to display specific letter of c strings or display the cstring without some spec letters, cna anyone teach me how to display it backwards?
Apr 10, 2011 at 6:16pm
You'll have to have a for loop.
Apr 10, 2011 at 6:44pm
how do u mean backwards?
from last character to first?

you will need while loop:

1
2
3
4
5
short len = strlen (name) + 1, x = -1;  //determine the size of "name"
const short size = len;
char backward [size];     //create temp char array (not char*)
do backward [x++] = name [--len];  //copy letter by leter from back to ahead
while (len != -1);  // do it until end of name 
Last edited on Apr 10, 2011 at 6:58pm
Apr 10, 2011 at 8:21pm
first of all what is "len" and your while loops seems unfimilar to me why do u have the DO then WHILE?
isn't it suppose to be

1
2
3
4
5
6
short len = strlen (name) + 1, x = -1;  //determine the size of "name"
const short size = len;
char backward [size];     //create temp char array (not char*)

while (len != -1);  // do it until end of name
do backward [x++] = name [--len];  //copy letter by leter from back to ahead  
Last edited on Apr 10, 2011 at 8:22pm
Apr 10, 2011 at 8:49pm
len is variable which takes lenght of string len as declared.

NO first do then while
or while only in your example.
Apr 11, 2011 at 5:37am
char* name = "Charmander";
As I know, this should be
char const* name = "Charmander";
in c++

1
2
char const* NAME = "Charmander";
std::cout<<NAME[3]<<"\n"; //maybe this would be easier to read 


1
2
3
4
5
6
int const LENGTH = static_cast<int>(strlen(NAME) - 1); //because the return type of strlen is size_t
for(int i = LENGTH; i >= 0; --i)
{
  std::cout<<NAME[i];
}
std::cout<<"\n";


I think using std::string would make things easier
1
2
3
  std::string const name = "Charmander";
  std::copy...
  std::cout<<"\n";


or just using the algorithm of stl
1
2
  char const* NAME = "Charmander";  
  std::reverse_copy... 
Last edited on Apr 11, 2011 at 6:55am
Topic archived. No new replies allowed.