checking char array for specifics

Trying to create a save game file, I ask the user to enter a name of his character. I then wish to check the character array for things like symbols and numbers, as I don't want to deal with that when constructing my saves. I am, however doing something wrong. I believe my fault is most likely how i'm handling the char array. Perhaps I shouldn't even be using a char array, or maybe it's the getline part. Anyways, here is the code.

	char playerName[10];
	std::cout<<"Please type a name. (Up to 10 Characters long, Letters only)\n\n";
	std::cin.getline (playerName, 9);
	for (int count = 0; count < 10; count++) 
		if (isalpha(playerName[count])); 
		else if (isspace(playerName[count]));
		else {std::cout<<playerName[count]<<" is an invalid character.\n"; goto lpNameCreation;}
	std::cout<<"Your name will be "<<playerName[10]; 

It compiles, but I get crazy results for the values when I look at the debug info.
Last edited on
playerName[10] is out of bounds. The indices of an array of 10 elements range from 0 to 9. But even if it was a valid location you would still print only the last character the user entered (by the way, if the name was 9 character long it wouldn't print anything because getline() automatically puts a '\0' at the end of the array, and if it was less than 9 characters it would print random data).

Instead of using a char array you could use an std::string. You wouldn't need to worry about how long the name is. The version of getline that uses strings is a global function.
Also note that cin.getline() reads n-1 characters, because it reserves the last element in the array to write the '\0'. In your code the name can be at most 8 characters long.

Using goto is considered bad practice. You may want to consider rewriting the function using a do-while.

The way you wrote the checks in the for loop are a bit weird but they work.

Why do you need ignore() on line 4?
Last edited on
The only reason I use the cin.ignore is when I use cin>>

If I try to use cin>> and my program SKIPS right over it during test run, then I add in a cin.ignore so all the keys previously pushed won't automatically input themselves when the program looks for input.

Btw, you said that I should make it a string and wouldn't need to put a limit on it. Well I WANT a limit on it. It's an easy text base game that i'm writing, but i'm trying to format it so that each "Day" in game shows certain amount of player info at the top. This is a console app, so if someone is to name themselves "reallyreallylong stringwithwaytoomanychars" then the format would be thrown off because the name is SO long.

So IS it possible to limit the inputs on a string?
Limiting the characters the user can type, I don't think so. You can crop the string to make it 10 chars long.
Topic archived. No new replies allowed.