EDIT: getline
is not standard C, and it is only recognized by POSIX systems. Another solution is to use fgets
that works for both OSes. I provided both examples.
As others have already pointed out, you are making some mistakes:
- Unsafe practice when getting input from the user.
- Always starting from 15 even if the input string has less chars.
I have created a little example with dynamic allocation that works with more than 15 characters and fixes the afore-mentioned issues. Comments inline to key points.
Example: getline - POSIX
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
// Idea from https://stackoverflow.com/questions/7709452/how-to-read-string-from-keyboard-using-c
char *line = NULL; /* forces getline to allocate with malloc */
size_t len = 0; /* ignored when line = NULL */
ssize_t read;
read = getline(&line, &len, stdin);
if (read > 0)
{
printf ("\n String from user: %s\n", line);
}else
{
printf ("Nothing read.. \n");
return -1;
}
// Now we need the same amount of byte to hold the reversed string
char* rev_line = (char*)malloc(read);
// "read-1" because we start counting from 0.
for (int i = 0, j = read-1; i < read; i++, j--)
{
rev_line[i] = line[j];
}
printf("%s\n",rev_line);
free (line); /* free memory allocated by getline */
free(rev_line);
return 0;
}
Example: fgets - C standard
fgets
does not return the number of characters read, so it has to be chained with strlen
to decide how many characters to allocate for the reversed string.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
int main (int argc, char *argv[]) {
char line[LINE_MAX];
size_t len = 0; /* ignored when line = NULL */
ssize_t read;
if (fgets(line, LINE_MAX, stdin) != NULL)
{
line[strcspn(line, "\n")] = '\0'; //fgets() reads the \n character (that's when you press Enter).
read = strlen(line);
printf ("\n String from user: %s\n", line);
}else
{
printf ("Nothing read.. \n");
return -1;
}
// Now we need the same amount of byte to hold the reversed string
char* rev_line = (char*)malloc(read);
for (int i = 0, j = read-1; i < read; i++, j--)
{
rev_line[i] = line[j];
}
printf("%s\n",rev_line);
free(rev_line);
return 0;
}