The fundamental error in your code is that you are using the &&
operator in the test inside your while
loop, whereas you should be using the ||
operator: if either of the conditions is true, then add the character to the output string.
Also, your doo
function is declared as returning an int
but it doesn't return anything: I fixed this in the code below by returning j
(the count of characters copied) but, as you never use that, you may want to redeclare the function as void
, instead.
You are also attempting to print p
with the puts
function, where you most likely want to print q
(I can put this one down to a typo).
Lastly: Never use the gets
function! Why is the gets function so dangerous that it should not be used? Use fgets()
, instead - it's much safer, as it will never read in more characters than you tell it to, so the buffer won't overflow (if you specify the correct size).
Here's a 'fixed' version of your code, with comments added where I've made changes:
#include <stdio.h>
char q[50];
int doo(int p, int n, char* s)
{
int i = 0, j = 0;
while (s[i] != '\0') {
if ((i < p) || (i > (p + n))) { // Need OR not AND here
q[j] = s[i];
++j;
}
i++;
}
q[j] = '\0'; // Add nul terminator (don't need if only calling once, but best to have it anyway)
puts(q); // Should be printing "q" (result string) NOT "p" (position).
return j; // MUST return something - here, the count of characters
}
int main()
{
char s[50];
int n, p;
printf("<--program by gautam-->\n");
printf("enter the string-->");
fgets(s, 50, stdin); // NEVER use gets - it's been removed from the language!
printf("\nenter the numbers of character to be deleted and position-->");
scanf("%d%d", &n, &p);
--p;
doo(p, n, s);
return 0;
}