Repeated your code then added some comments
void reverse_string(std::string input)
Arguably if you don't intend to alter input, you should make it const
{
int N = input.length();
char buffer[100];
What if someone passes a string of 100 or more characters?
char* ptr1;
char* ptr2;
ptr1= ptr2 = const_cast<char*>(input.c_str());
Add spaces for readability. while (*ptr2) { ptr2++; }
ptr2--;
What is wrong with char const *ptr2 = ptr1 + strlen(ptr1) - 1;
or are you forbidden to use the standard library? Also (pedantically) a std::string may contain multiple 0 bytes, in which case this would only reverse the first part of it.
int i =0;
while(ptr2 >= ptr1)
I'd have put a space after the while
here, as it isn't a function call. But that's picky.
{
buffer[i] = *ptr2;
ptr2--;
i++;
It's more usual in c++ to use pre-increment and pre-decrement.
}
buffer[i+1]='\0';
N
should be declared here, not waaaay up there (though given the performance of string::length it's probably not worth having a separate variable for it).
for(int j=0;j<N;j++)
{
printf("%c",buffer[j]);
}
Given buffer is a null terminated string you can just use puts
to output it. But see below
std::cout << endl;
- For consistency with the rest of the code, that should be
std::endl
;
- Using
endl
is arguable. It flushes the output stream for you and this can be a serious performance hit. In any case "\n"
is a lot less typing than std::endl
;
- Why mix C and C++ output methods? It'd be clearer to write one of
std::cout << buffer << "\n";
or
printf("%s\n", buffer)
.
}
printf
andstdout << ...
. \$\endgroup\$