Here is the code
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char a[20],rev[20];
printf("enter the string");
scanf("%s",a);
int len=strlen(a);
for(int i=0;i<len;i++)
{
rev[i]+=a[len-i-1];
}
printf("%d \t \n string is \t %s",len,rev);
getch();
}
It was correctly working when we gave it a string without spaces:
input: welcome
len:7
output: emoclew
When we give it a string with a space:
input : welcome to this world
len:7
output:some other ascii chars that I have not seen so far. and the "len" is again 7 only
When I change the following statement:
scanf("%s",a) to gets(a);
I get:
input :welcome to this world
len:21
output : something different. not the reverse of string...
In this case "len" is correct but the output is wrong.
What is really happening? What is the problem with the above code?
scanf("%s",a). You cannot know how long the input is, so you must use a function that takes the buffer size as argument.gets, it will let you input as many characters as you want, over-run your buffer, and potentially crash your program