I can't find the error.When I was running it, it basically sidesteps this fgets(a,n,stdin) and directly executes line 30-string is not palindrome.I am attaching the error.. Code: #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char a[20]; int n,c; c=0; printf("enter the size of the string "); scanf("%d",&n); printf("enter the string "); fgets(a,n,stdin); for(int i=0;i<(n-1)/2;i++) { if(a[i]==a[n-1-i]) { c=0; } else { c=1; break; } } if(c==0) printf("string is palindrome"); else printf("string is not palindrome"); return 0; } Someone please help!
scanf is crap, use fgets instead. Read the input into a string, then use atoi to convert that string to a number (or sscanf if you're a glutton for punishment). scanf is the cause of this problem. Your input is "5 <enter>", so scanf reads the 5 and converts it to a 5, but it stops converting at the first non-numeric character, which is the <enter>, which it leaves on the input stream. When you call fgets, the <enter> is still there, so it reads that as a blank string and so you don't get prompted.
I am using fgets but that is also causing the same problem. Code: #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char a[20]; int n,c; c=0; printf("enter the size of the string "); scanf("%d",&n); printf("enter the string "); fgets(a,n,stdin); for(int i=0;i<(n-1)/2;i++) { if(a[i]==a[n-1-i]) { c=0; } else { c=1; break; } } if(c==0) printf("string is palindrome"); else printf("string is not palindrome"); return 0; } here it is also not executing fgets.The problem which i think is the newline that is left in the buffer after inputting "5 <enter>" .So how to remove newline? I mean to input the number i have to use scanf.So there is always a newline in the input buffer.So the problem persists.I am attaching a pic of the problem/error.So how to solve this...
>>I am using fgets >>scanf("%d",&n); Look again. >>to input the number i have to use scanf Why? There is a function to clear stdin but I can't remember what it is. fgets/atoi is a much better solution to the problem. But if your teacher has said you have to use it then you have to use it, in which case use fgets after the scanf to read the newline into a dummy buffer which you can then forget about. Comment it with something like "//ugly hack because scanf is a piece of crap".