Actually, your loop has a bug. You assign a with a value that could be outside the bounds of the array. Other thoughts:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buffer[BUFSIZ];
/*
* Prompt the user. Ensure that the prompt is displayed.
*/
fputs("Please enter a string: ", stdout);
fflush(stdout); /* http://www.eskimo.com/~scs/C-faq/q12.4.html */
/*
* Get one line of input.
* Checking return values is a good habit to have.
*/
if ( fgets(buffer, sizeof(buffer), stdin) != NULL )
{
size_t i; /* strlen() returns a size_t */
/*
* Look for a newline ('\n') in the input string.
* If found, replace it with a terminating null character ('\0').
*/
char *ch = strchr(buffer, '\n');
if ( ch != NULL )
{
*ch = '\0';
}
/*
* Set the index to the end of the string.
*
* If we had a 3-character string "abc", strlen() would return 3.
* This would mean that buffer[0] == 'a', buffer[1] == 'b',
* buffer[2] == 'c', and buffer[3] == '\0' (the null termination).
*
* So we subtract 1 from strlen(buffer) so that buffer[i] is the
* last character immediately preceding the null termination.
*/
i = strlen(buffer) - 1;
do
{
putchar(buffer[i]);
} while ( i-- > 0 ); /* we want to print until buffer[0] and then stop */
/*
* It is a good idea to make sure programs that output to the stdout
* finish with a newline.
*/
putchar('\n');
}
return 0;
}
/* my output
Please enter a string: Hello my nick is whtpirate
etaripthw si kcin ym olleH
*/