pointers and char functions without c++ library

Pages: 12
Your forward and reverse functions already use <cstring>'s strlen function to find the passed C string's length. Create your own strlen function and use that in your other two functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int my_strlen(const char* start)
{
   const char* end = start;

   // loop until '\0' is found
   // incrementing the position with each loop
   while (*end++ != '\0');

   // using pointer math to get the number of characters in the C string
   // minus the '\0'
   return end - start - 1;
}

int main()
{
   char cstr[] = "Test string.";

   int len = my_strlen(cstr);

   std::cout << "The C string has a length of " << len << '\n';
}

The C string has a length of 12

Is this the best, most efficient way to do this? Probably not. But it should fulfill the requirements your instructor has set of using C string pointers and '\0'.

Could I use that function, to make the backwards function to print out: olleh
You could, if you have the proper loop that can iterate through a C string in reverse order.
What I have so far:


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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/*Preprocessors*/
#include <iostream> //includes basics
#include <string>
#include <cstring>
#include <iomanip>
#include <cstdlib>
//Chris Rachal ITP 232 Lesson 3 assignment

using namespace std;
//Function Prototypes
void getText(char words[]);
void printOriginal(char words[]);
void printReverse(char words[]);
void printBackwards(char words[]);





int main()
{
   /**************************************************************************************
   *This is such a fun class. I really enjoy learning all there is to know about
   *C++. Array stores this text. The program must print text in original, reverse,
   *backwards order as well as count the letters in each word. The program must
   *be able to: count the number of words, longest word length, and shortest word length
   ***************************************************************************************/

    char words[265];//Array to hold text

    getText(words);//Calls the function to store data into the array.
    printOriginal(words);
    printReverse(words);
    printBackwards(words);




    return 0;
}
//function definitions
//Function definition to have the user type text and store it into the array.
void getText(char words[])
{

    cin.getline(words, 256);//saves the data entered by the user.

    }
/***************************************************************************************/
//Function displays what the user is prompt to enter.
void printOriginal(char words[])
{
    cout<<endl;
    cout<<"Original Order"<<endl;

    char* p; //pointer for the array.
    p = words;

    while(*p != '\0')//checks the for last character
    {
        cout<<*p;
        p++;
    }
        system("pause");
}

/***************************************************************************************************************/
void printReverse(char words[])//Function displays text in reverse.
{

    cout<<endl;
    cout<<"\nReverse Order"<<endl;

    char *p;
    p = words;

    while(*p)
          {
            p++;

          }

          while(p-- > words)
          {
              cout<<*p;
          }

    system("pause");
}
/**********************************************************************************************************************/
void printBackwards(char words[])
{

    cout<<endl;
    cout<<"Backwards"<<endl;

    char* p;

   length = 0;
   while(*p[length])
   {
       ++len;
       return;
   }

}
/*************************************************************************************************************************/
//Function definition that counts the number of letters inside the array.
void stringLength(char words[])
{
    cout<<endl;
    int i = 0;
    count = 0;


    while(word[i++] != '\0')
    {
        count += 1;
    }

    cout<<"Number of words: "<<count;
    
    
}
/***********************************************************************************************************************/
//Function definition finds the longest word in the array. 
void longestWord(char words[])
{
    
    
    
    
    
}
/***************************************************************************************************************************/
//shortest word length_error








/****************************************************************************************************************************/
//number of letters in each word







/***************************************************************************************************************************/
Using pointers to C strings (char arrays), as was the requirement from the start:
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>

int my_strlen(const char[]);
void forward_print(const char[]);
void reverse_print(const char[]);

int main()
{
   char cstr[] = "Test string.";

   int len = my_strlen(cstr);

   std::cout << "The C string has a length of " << len << '\n';

   forward_print(cstr);

   reverse_print(cstr);
}

int my_strlen(const char start[])
{
   const char* end = start;

   // loop until '\0' is found
   // incrementing the position with each loop
   while (*end++ != '\0');

   // using pointer math to get the number of characters in the C string
   // minus the '\0'
   return end - start - 1;
}

void forward_print(const char cstr[])
{
   // get the C string's length
   int len { my_strlen(cstr) };

   // create a pointer to the beginning of the C string
   const char* cbegin { cstr };

   // create a pointer to one address past the last valid character of the C string
   // the address of the null terminator '\0'
   const char* cend { cstr + len };

   // create a for loop using pointer math
   for (const char* itr { cbegin }; itr != cend; itr++)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';
}

void reverse_print(const char cstr[])
{
   // get the C string's length
   int len { my_strlen(cstr) };

   // create a pointer to the last valid character in the C string
   const char* crbegin { cstr + len - 1 };

   // create a pointer to the address one element before the first valid character
   const char* crend { cstr - 1 };

   // for loop using pointer math
   for (const char* itr { crbegin }; itr != crend; itr--)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';
}

C string pointers that emulate C++ container iterators.
@Furry Guy yeah you're right. You're a wizard. Going to grab some red bulls and coming back to get this some progress. I will make the changes.
ok, got it changed I don't think I missed anything.

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*Preprocessors*/
#include <iostream> //includes basics
#include <string>
#include <cstring>
#include <iomanip>
#include <cstdlib>
//Chris Rachal ITP 232 Lesson 3 assignment

using namespace std;
//Function Prototypes
void getText(char cstr[]);
void forward_print(const char cstr[])
void reverse_print(const char cstr[])
void print_backwards(const char cstr[]);





int main()
{
   /**************************************************************************************
   *This is such a fun class. I really enjoy learning all there is to know about
   *C++. Array stores this text. The program must print text in original, reverse,
   *backwards order as well as count the letters in each word. The program must
   *be able to: count the number of words, longest word length, and shortest word length
   ***************************************************************************************/

    char cstr[265];//Array to hold text

    getText(cstr);//Calls the function to store data into the array.
    int len = my_strlen(cstr);
    forward_print(cstr);
    reverse_print(cstr);
    print_backwards(cstr);
    
    




    return 0;
}
//function definitions
/**************************************************************************************/
//Function definition to have the user type text and store it into the array.
void getText(char cstr[])
{

    cin.getline(cstr, 256);//saves the data entered by the user.

    }
/***************************************************************************************/
//Function displays what the user is prompt to enter.
void forward_print(const char cstr[])
{
    
    cout<<"Original Order"<<endl;
   // get the C string's length
   int len { my_strlen(cstr) };

   // create a pointer to the beginning of the C string
   const char* cbegin { cstr };

   // create a pointer to one address past the last valid character of the C string
   // the address of the null terminator '\0'
   const char* cend { cstr + len };

   // create a for loop using pointer math
   for (const char* itr { cbegin }; itr != cend; itr++)
   {
      cout<< *itr << ' ';
   }
   cout<<endl;
   system("pause");
}

/***************************************************************************************************************/
void reverse_print(const char cstr[])
{

    int len {my_strlen(cstr)};
    
    const char* crbegin {cstr + len - 1};
    
    const char* crend {cstr - 1};
    
    for(const char* itr {crbegin}; itr != crend; itr--)
        {
            cout<<*itr<<' ';
        }
        
            cout<<endl;
    system("pause");
}
/**********************************************************************************************************************/


/*************************************************************************************************************************/
//Function definition that counts the number of letters inside the array.

/***********************************************************************************************************************/
//Function definition finds the longest word in the array. 
void longestWord(char cstr[])
{
    
    
    
    
    
}
/***************************************************************************************************************************/
//shortest word length_error








/****************************************************************************************************************************/
//number of letters in each word







/***************************************************************************************************************************/
There are a couple of things I would change:

1. Change the getText function to include the size of the C string you pass to it.
void getText(char cstr[], int size);

This function is the only time you have no means to determine the length of the string, it hasn't been entered yet. By including the maximum allowed size of the C string lets you choose a different size as wanted.
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
#include <iostream>

void getText(const char[], int size);
int my_strlen(const char[]);
void forward_print(const char[]);
void reverse_print(const char[]);

int main()
{
   const int size { 256 };

   char cstr[size];

   getText(cstr, size);

   forward_print(cstr);

   reverse_print(cstr);

   // print_backwards(cstr);  // <--- this function no longer exists, remove
}

void getText(char cstr[], int size)
{
   std::cin.getline(cstr, size);
}

You choose later to have a C string length of 80 (79 characters + '\0') you need to change only one line of code. Line 8 in main. You should never use "magic numbers."
https://www.jarchitect.com/QACenter/index.php?qa=155&qa_1=no-magic-numbers

2. Why are you getting the C string's length in main? You are doing nothing with it.

If you were to print out a message of the string's length, then fine.
std::cout << "The C string has a length of " << len << '\n';

3. You are including headers for library features you are not using. Not that it will affect the program, it is just a bit of overkill. A "toss in the kitchen sink" kind of thing.

It might take the preprocessor a couple of CPU cycles to slog its way through header code it doesn't need to.

With the code you currently have all you need is <iostream>.

4. using namespace std;. Don't. Period.
https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

I don't use it, I fully qualify each object from the std namespace with std::

Personal pet peeve of mine, I refuse to use it. I consider it being lazy.

Others will disagree. YMMV.

5. Variable names. I was very particular in my name choices in the forward and reverse display functions. I was using the names of C++ container iterators.

Look at the names of the predefined iterators for std::string.
https://en.cppreference.com/w/cpp/string/basic_string

Look kinda familiar, don't they.

Having variable names like those is a good hint to your instructor you likely didn't write the code yourself.

6. Now, other people have given you decent code for the forward print function that does not use the iterator style for the for loop.

I wrote both the print functions deliberately to emulate iterator usage. Easier IMO to covert C string functions using iterator emulation to functions that take a std::string that CAN use iterators:
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
void forward_print(const std::string& str)
{
   for (std::string::const_iterator itr = str.cbegin(); itr != str.cend(); itr++)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';
}

void reverse_print(const std::string& str)
{
   for (auto itr = str.crbegin(); itr != str.crend(); itr++)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';
}


Now, onto the commentary section......

You're a wizard.

7. ROFL. Not one bit, really. I simply tried to follow the instructions you were given, C strings and pointers, and purposefully wrote code in a way that gave a bit of insight into C++ containers and iterators.

Regular array pointers and C++ container iterators are superficially much the same. They act much the same, pointing to elements of the container and can be manipulated using rudimentary pointer math.

I routinely make more than my share of dumb "what was I thinking?!?" mistakes.

There are other little nitpicky details I might tell you about (not using return 0; or system("pause); ) but I've bored you enough already.
Last edited on
I just got on, @Furry Guy. Thanks the the advice. I did the system pause after each output because it was in the instruction. I don't get why, but I said ok. Just woke up so I'm going to look everything over. To be honest, my book, I really don't like it that much. I have learned properly more asking for help can here than anything. I'm always struggling with each assignment.
I tried to build and compile, but I got some errors on the for loops. This stuff is killing my confidence lol.
I got some errors on the for loops.

And those errors might be? Copy and paste 'em here, inside some output tags. (the button to the right of the <> code tags button)

Letting us know what your compiler is could be helpful as well.

I'm always struggling with each assignment.
C++ has a very steep learning curve. Especially when the course of instruction or the instructor teach fairly advanced concepts before what should be the basics.

Regular arrays and pointers are not IMO beginners' topics. Nor are they exclusively C++ topics. They are rooted in C.

Teaching C++ as if it were some super advanced variant of C makes things much more difficult to beginners than it needs to be.

Learn to program books usually are years out of date. The same goes for classroom course outlines.

The language is updated fairly often, teaching materials and instructors aren't.

Now, with that all ranted about, I took your last posted source, changed a couple of things, added a couple of things and formatted it so the meat stands out from the bones a bit more (no excessive whitespace that clutters things up):
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>

void getText(char[], int size);
int my_strlen(const char[]);
void forward_print(const char[]);
void reverse_print(const char[]);

int main()
{
   // const int size { 256 };

   // I changed the size to show why passing an array's size into functions is preferred
   const int size { 80 };

   char cstr[size];

   getText(cstr, size);

   forward_print(cstr);

   reverse_print(cstr);
}

void getText(char cstr[], int size)
{
   std::cout << "Enter a line of text:\n";

   std::cin.getline(cstr, size);

   std::cout << '\n';
}

int my_strlen(const char start[])
{
   // create a pointer to the first character in the C string
   const char* end { start };

   // loop until '\0' is found
   // incrementing the position with each loop
   while (*end++ != '\0');

   // using pointer math to get the number of characters in the C string
   // minus the '\0'
   return end - start - 1;
}

void forward_print(const char cstr[])
{
   // get the C string's length
   int len { my_strlen(cstr) };

   // create a pointer to the beginning of the C string
   const char* cbegin { cstr };

   // create a pointer to one address past the last valid character of the C string
   // the address of the null terminator '\0'
   const char* cend { cstr + len };

   // create a for loop using pointer math
   for (const char* itr { cbegin }; itr != cend; itr++)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';

   system("pause");
   std::cout << '\n';
}

void reverse_print(const char cstr[])
{
   // get the C string's length
   int len { my_strlen(cstr) };

   // create a pointer to the last valid character in the C string
   const char* crbegin { cstr + len - 1 };

   // create a pointer to the address one element before the first valid character
   const char* crend { cstr - 1 };

   // for loop using pointer math
   for (const char* itr { crbegin }; itr != crend; itr--)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';

   system("pause");
}

Enter a line of text:
I pity the fool required to use system("pause")

I   p i t y   t h e   f o o l   r e q u i r e d   t o   u s e   s y s t e m ( " p a u s e " )
Press any key to continue . . .

) " e s u a p " ( m e t s y s   e s u   o t   d e r i u q e r   l o o f   e h t   y t i p   I

One thing to note: all of my variable initializations use "uniform initialization." Something available in C++11 or later.
https://mbevin.wordpress.com/2012/11/16/uniform-initialization/

Using "normal" C++ initialization (int len = my_strlen(cstr);) makes the code compilable with pre C++11 standards.
Topic archived. No new replies allowed.
Pages: 12