Is it considered bad practice to pass string literals as char*, when an array and not a c-string is expected by the function? From my code:
char ConsoleIO::GetNextChar(string prompt, char* choices, int numChoices) {
// Loop until valid input, or 10 times.
for (int i = 0; i < 10; i++) {
Write(prompt);
char* buffer = new char[200];
cin.getline(buffer, 200);
char choice = tolower(buffer[0]);
if (in(choice, choices, numChoices)) {
return choice;
}
WriteLine("Invalid choice.");
}
// Just return the first choice as the default.
return choices[0];
}
// In main:
char userChoice = ConsoleIO::GetNextChar("Make a selection: ", "234", 3);
It compiles, but is it bad practice?
1 Answer 1
When a C or C-related programmer sees char*
they're going to naturally think of passing in a C-string. In my opinion, it's absolutely fine to do that. If you want to invoke an array of characters in C, I'd do it like this:
char ConsoleIO::GetNextChar(string prompt, char[] choices, int numChoices)
But, you're in C++ so you should use a std::vector<char>
and then don't pass in numChoices
, like this:
char ConsoleIO::GetNextChar(string prompt, std::vector<char> const& choices)
Also, you have a bug. You aren't ever delete
ing buffer
, which means it's leaking.
-
\$\begingroup\$ I appreciate the input, especially on the memory leak. Thanks! \$\endgroup\$Java Matrix– Java Matrix2015年12月06日 02:01:14 +00:00Commented Dec 6, 2015 at 2:01
-
\$\begingroup\$ I suggest use of
std::vector<char> const& choices
. \$\endgroup\$R Sahu– R Sahu2015年12月06日 08:30:23 +00:00Commented Dec 6, 2015 at 8:30 -
\$\begingroup\$ @RSahu Excellent point! I'll update it. \$\endgroup\$user1118321– user11183212015年12月06日 15:33:36 +00:00Commented Dec 6, 2015 at 15:33
"234"
is aconst char[]
which cannot be converted to achar *
. You should at least get a warning. \$\endgroup\$