A newbie to C++ here. I need help with counting array length's, I have an array that i only want the user to be able to enter up to ten characters, but lets say if i enter eleven, the array is expanded out to eleven charactes, and i dont want that. i want the array to be cut off at ten.

so far this is the code that i have.

/* Welcome to Dungeon, This will be a simple game */
/* that will require the users name, and confont him */
	/* with a maze in which he must navigate! */
					 /* Good Luck! */
#include <iostream.h>
int main()
{
char UsrName[10];
//will prompt user for name to be used throughout the game
cout<<"Welcome to Dungeon!\nPlease enter your name!\nYour name can only be up to 10 characters long.\n";
//write a function to stop array from becoming over ten characters long
cin>>UsrName;
cout<<"Welcome "<<UsrName<<"!";
}

i need to count the array on character at a time in a loop, after each iteration it will check to see what number of the count that it is on. if it is at ten it will simply cut off the end of the array leaving with a nice neat little array. Any help would be greatly appreciated. As to the fact that i am a newbie to C++ any help on better ways to write my code would be much appreciated.

I would recommend getline() instead of cin >>:

cin.getline(UsrName, 10, '\n');

Here's more information about getline() and its paramaters.


Hope this helps,
- Stack Overflow

Comments
Thanks you very much for that comment, ill definatly look into it! --KT

If you're using C++, why aren't you using std::string?

because honestly im very new to it, and since my dad works from about 9 in the morning untill 11 at night, i dont get chances to ask him very often. Which is why your going to see alot of posts asking for help from mee ;)

Hello,

You might want to send your dad an email then :)

IF Memory serves, you can read the string into a [40] string array (for safety) and then do a string copy of the first 10 characters. Don't forget the 11th character for internal storage of your \n (return) so that things align nicely inside of the program.

Of course, that will not work if you want to error check. You might then use a strlen to see if the array is X size, and then use if-logic to see if people are following directions.

Christian

Here is the updated code thus far. Im looking for a way to repeat steps in the switch if they enter invalid term for continuing. any help would be greatly appreciated!

/* Welcome to Dungeon, This will be a simple game */
/* that will require the users name, and confont him */
	/* with a maze in which he must navigate! */
					 /* Good Luck! */
#include <iostream.h>
int main()
{
char UsrName[10];
//will prompt user for name to be used throughout the game
cout<<"Welcome to Dungeon!\nPlease enter your name!\nYour name can only be up to 10 characters long.\n";
cin>>UsrName;
//write a function to stop array from becoming over ten characters long
if (strlen(UsrName) > 10)
	{
	 do
	 {
	 cout<<"You have entered a name too long!\n";
	 cin>>UsrName;
	 }
	 while (strlen(UsrName) > 10);
	 }
cout<<"Welcome "<<UsrName<<"!";
cout<<"\nYou are about to embark on the shortest god damn maze of your life..\nstraight forward is the exit.\nThere is no left nor right just yet!\nHave fun "<<UsrName<<"!\n";
//lets call us some variable, X will be used to determin ContExit (continue or exit)
//if contexit is 1 we continue 
//if contexit is 0 we exit
int x, ContExit;
cout<<"\n1 to continue and 0 to exit\n";
cin>>x;
if (x == 1)
	 {
	 ContExit = 1;
	 }
else
	{
	 ContExit = 0;
	 }
//write a switch statement that will exit or start if exit = 0 or cont = 0 respectivly
switch (ContExit)
		{
		case 0: cout<<"\nCya Next time!";
				return 0;
		case 1: cout<<"\nYou are faced with one exit:\n1: North\n";
			int y;
				cin>>y;
				if (y == 1)
				 {
				 cout<<"\nThank you for playing the game"<<UsrName<<"!\n"<<"Hope to see you next time!\n";
				 return 0;
				 }
			else
					{
					cout<<"\nYou didnt enter a valid Direction!\n";
					}
		}
return 0;
}

Hello again,

I believe I understand what you are looking to do. To further clarify, are you looking to re-ask the question of continuing if not 0 or 1 [invalid] by the users input?

If so there are 2 main ways to accomplish this:

  • Use the goto statement
  • Split your program into different functions

The second is most recommended, though I will explain both.

Using goto
Explaining the goto statement first, lets look at our modifications:

Above the line:

cout<<"\n1 to continue and 0 to exit\n";

Lets put:

[b]ask:[/b]
cout<<"\n1 to continue and 0 to exit\n";

Simple. C provides the infinitely-abusable goto statement. The goto statement labels to branch to. ask here is our scope of a label in the entire function.

Also, instead of setting ContExit = 0; in your else to find x, lets set it to x so we know what was entered. Even if 0 was entered, we would still know about it. Ex:

else {
	ContExit = x;
}

After this, in your switch statement include the default case. Why? The case labeled default is executed if none of the other cases are satisfied. Exactly what we need! In the case, we tell the compiler to "goto ask;"

Here is a look:

switch (ContExit) {
	case 0:
		...
	case 1:
		...
	default:
		goto ask;
}

Now when you compile, if the user did not type 0 or 1, it will go back and ask them what they want infinitely until they choose a valid choice.

Splitting your code
This way is more often reliable, and less dependant. This way, we can split sections of your code in seperate functions. Have a look:

#include <iostream.h>

// Put calls up here so compiler doesn't whine
void getinput(int *, char *);
// Make this one return int, so [b]return 0[/b] doesn't conflict
int makechoice(int, char *);

// Your own function seperate from main() for easy call
void getinput(int *choice, char *name) {
	int x;

	cout<<"\n1 to continue and 0 to exit\n";
	cin>>x;

	if (x == 1)
		*choice = 1;
	else
		*choice = x;

	makechoice(*choice, name);
}

// Here is the decision making factor
int makechoice(int choice, char *name) {
	switch (choice) {
		case 0: cout<<"\nCya Next time!";
				return 0;
		case 1: cout<<"\nYou are faced with one exit:\n1: North\n";
			int y;
			cin>>y;
			if (y == 1) {
				cout<<"\nThank you for playing the game"<<name<<"!\n"<<"Hope to see you next time!\n";
				return 0;
			}else {
				cout<<"\nYou didnt enter a valid Direction!\n";
			}
		default:
			// call again in case we dont get the results we want
			getinput(&choice, name);
	}
	return 1;
}

int main() {
	// Our local variables
	int ContExit;
	char UsrName[10];

	cout<<"Welcome to Dungeon!\nPlease enter your name!\nYour name can only be up to 10 characters long.\n";
	cin >> UsrName;

	if (strlen(UsrName) > 10) {
		do {
			cout<<"You have entered a name too long!\n";
			cin>>UsrName;
		} while (strlen(UsrName) > 10);
	}

	cout<<"Welcome "<<UsrName<<"!";
	cout<<"\nYou are about to embark on the shortest god damn maze of your life..\nstraight forward is the exit.\nThere is no left nor right just yet!\nHave fun "<<UsrName<<"!\n";

	// Call our function here
	getinput(&ContExit, UsrName);

	return 0;
}

I commented our new areas. Most is self-explanatory. Though, lets take a quick look on how this works:

Review
We make two functions outside of main() called getinput() and makechoice().
Next we pull out the input factor and move it into getinput(). getinput() takes two parameters, your choice, and name. Even though the choice hasn't been given yet, we will send the memory address of ContExit to getinput(). This will allow us to change the variable state somewhere else, and if you come back to main() and check ContExit's value, it will be what getinput() set it to last.

After that, we call on makechoice(). makechoice() also takes two parameters, choice and name. This time, we don't send the memory address of our choice to this function because we already know the answer. makechoice() determines what the outcome of the program will do next. 0 exits, 1 moves on, invalid re-asks the question using the default label. We send the memory address of choice in makechoice() back to getinput() for re-evaluation if an invalid choice was received. We also need some way to track your name, so we pass it around all of the functions.

Summary
I do hope this has shed some light on the issue, and can now help you understand more of the C language.

If you have any questions, please feel free to ask. I will try to help you further in any way possible to clearly understand the syntax above.


- Stack Overflow

Wow that was all very very good input, give me a little time to go over it and see whats with what, so i can write up some questions and post them looking for answers!

Hello again,
Splitting your code
This way is more often reliable, and less dependant. This way, we can split sections of your code in seperate functions. Have a look:

#include <iostream.h>
 
// Put calls up here so compiler doesn't whine
void getinput(int *, char *);
// Make this one return int, so [b]return 0[/b] doesn't conflict
int makechoice(int, char *);
 
// Your own function seperate from main() for easy call
void getinput(int *choice, char *name) {
	int x;
 
	cout<<"\n1 to continue and 0 to exit\n";
	cin>>x;
 
	if (x == 1)
		*choice = 1;
	else
		*choice = x;
 
	makechoice(*choice, name);
}
 
// Here is the decision making factor
int makechoice(int choice, char *name) {
	switch (choice) {
		case 0: cout<<"\nCya Next time!";
				return 0;
		case 1: cout<<"\nYou are faced with one exit:\n1: North\n";
			int y;
			cin>>y;
			if (y == 1) {
				cout<<"\nThank you for playing the game"<<name<<"!\n"<<"Hope to see you next time!\n";
				return 0;
			}else {
				cout<<"\nYou didnt enter a valid Direction!\n";
			}
		default:
			// call again in case we dont get the results we want
			getinput(&choice, name);
	}
	return 1;
}
 
int main() {
	// Our local variables
	int ContExit;
	char UsrName[10];
 
	cout<<"Welcome to Dungeon!\nPlease enter your name!\nYour name can only be up to 10 characters long.\n";
	cin >> UsrName;
 
	if (strlen(UsrName) > 10) {
		do {
			cout<<"You have entered a name too long!\n";
			cin>>UsrName;
		} while (strlen(UsrName) > 10);
	}
 
	cout<<"Welcome "<<UsrName<<"!";
	cout<<"\nYou are about to embark on the shortest god damn maze of your life..\nstraight forward is the exit.\nThere is no left nor right just yet!\nHave fun "<<UsrName<<"!\n";
 
	// Call our function here
	getinput(&ContExit, UsrName);
 
	return 0;
}

- Stack Overflow

what are the *'s in the makechoice and such? what do they do, are they pointers? or do they serve some other purpose? since i am new to this, i am very lost as to alot of the syntax of it all.

Questions:
1. I dont understand the two void inputs
2. I dont know what the purpose of the *'s are, pointers maybe?
3. I dont understand what the char *name is used for.

any chance that you can explain the different return 'some value' and what they mean do. in the code you say to return into so that return 0 doesnt conflict. so can you explain what would a return 0 incomapred to a return 5 or even a return int is.


((also side note, does anyone know of any good freebased compilers? i am currently using a really old version of borland C++ compiler, but its very ugly, and the syntax coloring is nonexistant at that. I've tried bloodshed, but it doesnt work, and i was hoping for somthing that had smart syntax. so if you start to type int a yellow box will appear with valid forms of int. kinda like dreamweavers ability to do that))

Questions

» I dont understand the two void inputs
What exactly do you mean?

» I dont know what the purpose of the *'s are, pointers maybe?
Yes, pointers. The reason you need the unary (*) operator, is because we sent the memory address to our function. Let me clarify. If a variable contains data here (d) and its memory address is here (m), I would need to get to (m)->(d) to access the data from the address sent.

Likewise, the * operator allows me to read the data from the address. Using the * will point to the data instead of looking or modifying the address:

int main() {
	int var;
	int *ptr;	// ptr is a pointer to nothing

	ptr = &var;	// our ptr's memory address points to 'var'

	ptr = 3;	// no no, ptr is our memory address
	*ptr = 3;	// exactly, now we are writing to our data
	
	// Like wise with "*choice = 1;" instead of "choice = 1"
}

I hope that makes sense. I wrote a tutorial on pointers in the C/C++ tutorial section. If you have further questions, you may find your answers there. Though, if not please feel free to ask here.

» I dont understand what the char *name is used for.
Quite simple. You will probably need to access the players name outside of main() sometime, like for instance makechoice(). We have to know the players name somehow, so we are just passing the data around to all of the functions in case one needs them. It's nothing fancy since arrays and pointers are close to each other.

Since we aren't looking for the memory address of our name, we will just pass the data (d) to all of our functions. As you may have seen originally, our main() function sends UsrName to getinput() first, then passes throughout the rest of the program. I hope that makes sense.

» The return value issue
This one is quite simple also. Every function has a return type, and must correspond to returing the same data type. A function provides a convenient way to encapsulate some computation, which can then be used without worrying about its implementation.

return-type function-name(paramater declarations, if any)
{
	declarations
	statements
}

We all know 0 is an integer, meaning if we declared makechoice() as void for the return-type, the compiler would whine letting us know its differences. That is why we declared it as an int, hence int makechoice(int, char *);

To make this even simpler, we can only exchange the same type of data. You could use the "void *" return-type and send any type of data, but you would need to know how to convert it back. That's a whole different topic in itself. Since makechoice() is the decision making factor of your program, we need to end it there or let it continue, which is why we must allow it to return 0. All that does is terminates your program now.

» What would a return 0 incomapred to a return 5?
The return statement stops execution and returns to the calling function. When a return statement is executed, the function is terminated immediately at that point, regardless of whether it's in the middle of a loop, etc.

A void function doesn't have to have a return statement. When the end is reached, it automatically returns. However, a void function may optionally contain one or more return statements:

void myFunc(void) {
	return;
}

If a function returns a value, it must have a return statement that specifies the value to return. It's possible to have more than one return, but the (human) complexity of a function generally increases with more return statements. It's generally considered better style to have one return at the end, unless that increases the complexity:

int myFunc(void) {
	return 0;	// non-zero value
}

» Does anyone know of any good freebased compilers?
Yes. Bloodshed Dev-C++ is a good one.

I hope this clarifies alot, and please feel free to ask more questions.


- Stack Overflow

sorry i forgot to clairfy that. the two void getinputs, how come their is two of them, is the first a dummy that will do nothing?

No problem.

I do it for good practice. Why? Because the first one is a declaration, the second one is the actual function:

// Our declaration
void getinput(int *, char *);

// Our function
void getinput(int *choice, char *name) {
	...

Now you may ask why I would do this. It's actually quite simple. If we have multiple functions, and they both call on each other we may run into a dilema:

// Lets not declare anything, just make up functions as we go
void funcA(void) {
	funcB();	// oh, what is funcB()? It hasn't been created yet
}

int funcB(void) {
	return 0;
}

int main() {
	funcA();

	return 0;
}

The reason why we create the declarations first is so our complier knows of our functions before we make them. Same goes for functions below main(), and when main() calls on them it's nowhere to be found. If we declare them first above main(), it'll will know what to do with them throughout the whole code.


Hope this makes sense,
- Stack Overflow

This article has been dead for over six months. Start a new discussion instead.