Argument passing clarification

Hello guys forgive the code dump but if i can direct you to the few lines I have highlited in bold about half way down, I am looking for some help not with the program but with my comment explanations, as i'm trying to be accurate.

The bit i'm not 100% on is where I have passed 2 character arrays to another function. I kind of stumbled across how to do it, and as far as i can work out this is best done with pointers and/or references but in my class we have not covered these yet (I only know of them because I bought a learning book for myself and have been jumping ahead)

So I was trying to do it without pointers and such and I seem to have found something that works, however I am not sure exactly how to explain what I have done in the comments beside that section. I started as you can see saying i have passed the character array by value but i suspect this is incorrect as from what I have read you do not pass character arrays by value, you pass by reference... Yet i have not created a reference alias or a pointer or anything... so how would I put across what exactly i have done ?

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
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
#include <iostream.h>	//for standard input and output
#include <conio.h>	//for clrscr and getch
#include <string.h>	//for character arrays

void menu_driven_interface();	      //function prototype.

void get_names();		      //function prototype.
void create_username(char[], char[]); //function prototypes...
void show_username(char[]);	      //...with passed argument datatype
				      //...for passing character arrays.
void get_number();		      //function prototype.
void evaluate_factorial(int);	      //function prototypes...
void display_factorial(int, int);     //...with argument for passing numbers.

int main()                            //main function.
{
 menu_driven_interface();             //calls the main menu function.

 getch();                             //to get keystroke before closing.
 return 0;                            //to indicate successful run.
}

void menu_driven_interface()          //function definition.
{
 int valid_menu_option;               //to store user's menu choice.

 do                                   //start of do-while loop.
 {                                    //main menu display statements.
  cout << "	Welcome to the EPOS Options Ltd." << endl;
  cout << "Network Administration & Statistics Department\'s" << endl;
  cout << "	Pilot \"One Stop Shop\" interface" << endl << endl;
  cout << "Please Select one of the following menu options:" << endl << endl;
  cout << "Option 1:  To generate a personal username" << endl;
  cout << "Option 2: To calculate a number\'s factorial" << endl;
  cout << "Option 3:   To exit from the application" << endl << endl;

  cin >> valid_menu_option;           //input for user's choice.
  cout << endl;                       //formatting.

  switch (valid_menu_option)          //branching switch statement to..
  {                                   //..continue depending on user choice.
   case 1:
     get_names();                     //calls get_names function..
     break;                           //..if menu option 1 is chosen.
   case 2:
     get_number();                    //calls get_number function..
     break;                           //..if option 2 is chosen.
   case 3:
     cout << "Press any key to exit application..." << endl;
     break;                           //exits switch and returns to main..
   default:                           //..if option 3 is chosen.
     cout << "You entered an invalid menu choice, only the options";
     cout << " \"1\" , \"2\" and" << endl; //in case of invalid input.
     cout << "\"3\" are allowed, please press return and try again" << endl;
  }
 } while (valid_menu_option != 3);    //test expression for do-while loop..
}                                     //..returns to menu unless 3 is chosen.

void get_names()                      //function definition.
{
 char forename[9], surname[14];       //declaring character arrays to store..
				      //..first and second names.
 cout << "Please enter your first name:	"; //ask user for input.
 cin >> forename;                          //get user input.
 cout << "Please enter your second name:	"; //repeat.
 cin >> surname;                                   //repeat.
 create_username(forename, surname);  //call create_username function while..
}                                     //..passing character arrays by value.

void create_username(char * fName, char * sName) //function definition..
{                                        //..including passed arguments.
 char username[16];                      //new character array declared.

 strncpy(username, fName, 1);
 strcat(username, sName);
 strlwr(username);

 show_username(username);
}

void show_username(char * uName)
{
 cout << "\n\nThe network username to be used is: ";
 cout << uName << endl;
 cout << "Press the Enter key to return to the main menu";
 getch();
 cout << endl << endl << endl << endl;
}

void get_number()
{
 int number_in;

 cout << "Please enter a number to calculate its factorial: ";
 cin >> number_in;

 evaluate_factorial(number_in);
}

void evaluate_factorial(int number_in)
{
 int factorial = 1, i = number_in;

 while (i > 1)
 {
  factorial = (factorial * i);
  i--;
 }

 display_factorial(number_in, factorial);
}

void display_factorial(int number_in, int factorial)
{
 cout << "\nThe factorial of " << number_in << " is: " << factorial << endl;
 cout << "Press the Enter key to return to the main menu";
 getch();
 cout << endl << endl << endl << endl;
}
Why are you trying to comment every line? IMO excessive comments are worse than no comments since they obscure the code, are hard to maintain the accuracy of the comments based on the code.

Your code should be self explanatory as much as possible. Use meaningful variable and function names, use parameter names in your function prototypes, etc, etc.

Keep the function prototypes looking the same as the function implementations, and use meaningful names:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Function prototypes
void create_username(char first_name[], char sur_name[]);

// Function implementation.
void create_username(char first_name[], char sur_name[])
{

}

...
//function call. IMO you don't need a comment your code is the comment.
//  Also the comment is incorrect. Arrays are  not passed by value, they are passed by pointer.
create_username(forename, surname);  //call create_username function while..
                                    //..passing character arrays by value


And be consistent with your naming schemes. You use names with embedded underscores in many places but you also seem to be mixing in camel case as well as all lowercase, try to stick to one method or the other.

Last edited on
Many areas you mention are out of my control as I must stick to the function names and such that I have been given for the assessment, sucks I know. We have also been told to comment extensively which is the only reason I am putting any in, I guess they want us to demonstrate we know what each line is doing, but if it does turn out to be too much I can at least easily delete some comments later.

Is passing by pointer what I have done ? I only ask because when I covered pointers in the book i'm using there was more to it, I would have needed a line like

char* ptrForename = &forename;

and then ptrForename would be my pointer.

Is what I have done just another way to do it ?
Last edited on
When you use the name of the array by itself, e.g. "forename", that is automatically a pointer (the address of the first element of the array), so your code should work, except for one thing...

you're using a character array (which is not null terminated by default). You have no control over the names. If a user enters a name longer than the size of your array you're stuffed. Furthermore, you have no way of knowing until your program crashes.

using cin in this way results in undefined behaviour.

I don't advocate the style of programming (neither yours above above nor my compromise below, you should be using std::string), but at the very least, force the names to be a length you know

Example:

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

using namespace std;

//Everything above this probably won't work with your old old compiler, so just ignore

int main()
{
        // with a char array
	char forename[10]; // for 9 characters and a terminating 0
	scanf("%9s", forename); // will read at most 9 characters
    
        // or with a string
	string surname;
	cin >> surname; // will read very long names
	surname.resize(14); // restrict to 14 characters

        // instead of strncpy and strcat
	string username = forename[0] + surname;
    cout << username << endl;
}


Lecture:

Judging from this code, you're using a very old compiler, even older than the 1998 standard. Given that people are already talking about C++14, I think you're being done / doing yourself a great disservice.

I appreciate that you may not be able to do much about the tools your lecturer gives, but you owe it to yourself to at least ask why this is the case, given that the newest and best compilers are available on multiple platforms, free of cost and open-source.

As you've taken the initiative in getting a book and going ahead of the class, i suggest that you go the whole way and and modernize in your own time, even if yo have to conform to old-timey methods in class.
I really don't recommend using C-stdio functions at all, just use the extraction operator properly:
1
2
3
4
#include <iomanip>
...
const int name_size = 10;
cin >> setw(name_size) >> forename;


Or even better yet use getline() instead.
1
2
const int name_size = 10;
cin.getline(forename, name_size);


And remember that the extraction operator doesn't allow spaces in the name, for that you will need the getline() function.


But as you've said a std::string would be the preferred option.
Thanks a lot for that info that clears it up for me. I'd be all over your string suggestion too as I have been through that chapter of the book (C++ in easy steps) and from what I can see it is so much simpler to work with strings rather than this 'pseudo-string / character array' method they are teaching us, i'd rather not be using things like strupr and such at all but it seems I have to stick to this for the 'official' assessment.

You're correct about the compiler we are using borland turbo c++ which seems to be from the late 80s, we're having to run it in dosbox and it's a complete nightmare to use honestly, simple things such as keyboard and mouse control are unreliable.

This is the first actual assessment for us - so far with the normal weekly exercises it has been ok for me to use visual studio 2013 and I am also using that as I work through the book so this is just one of those things where the assessment has to be done this way to satisfy the education authority. When I asked about using visual studio for this I was told I could use it to work on the program but I would have to transfer it to borland and make sure it was working there, so that's what I have done.

For the sizes of the array those have been stipulated by the assessment brief also so I'll leave those as is, however it's also part of the assessment to point out possible errors in testing sheets so I will be highlighting what you point out when it comes to that.

I appreciate the getline suggestion too and I would use that for sure but again on the assessment brief it lists the variables to be used and given what we have been given in class i'll stick to those methods for this.

If I have time when finished I may well do the whole program again with these suggestions, ignoring these stupid impositions and just doing it the way you guys describe, if nothing else for my own benefit.

thanks again
Last edited on
Topic archived. No new replies allowed.