0
Plz anyone tell me what is the problem with this code coach problem code?
#include <stdio.h> #include <string.h> int main() { char str[100]; gets(str); char ans[100]; int len = strlen(str); int i,j,k,temp; j=0; for(k=0;k<len/2;k++) { temp = str[k]; str[k] = str[len-k-1]; str[len-k-1] = temp; } for(i=0;i<len;i++) { if((str[i]>=65 && str[i]<=90) || (str[i]>=97 && str[i]<=122) || str[i]==32) { ans[j]=str[i]; j++; } } puts(ans); return 0; }
5 Answers
+ 2
The problem is that the string in `ans` is not null-terminated, so depending on what values where in that memory beforehand, you write more characters than you actually want. Either zero-initialize the array at the start or explicitly store a null character at the end of the string to make it work, i.e
char ans[100] = {0};
or
ans[j] = '\0';
puts(ans);
0
I tested your snippet with default
0
Did it run?
0
I mean did it give the required output?
0
I tested your snippet with default sample "d89%l++5r19o7W *o=l645le9H"
It did run, and it did output "Hello World"
I don't know why you get a problem, the only possible issue I see here is the use of gets() function which is deprecated. People avoid using gets() and use fgets() instead for now.
http://www.cplusplus.com/reference/cstdio/fgets/
(Edited)