I wrote a function that remove a given char from a string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* input_long(void);
void removeChar(char str[], char ch);
void main()
{
char *str, ch;
str = input_long();
printf("\nplease enter a char to be removed from the string: ");
scanf("%c", &ch);
removeChar(str, ch);
printf("the string after the removal is %s \n", str);
free(str);
}
void removeChar(char str[], char ch) //this function removing a given char from a given string//
{
int i, j = 0;
for (i = 0; str[i] != '\0'; i++) //looping the string until its end//
{
if (str[i] != ch) //by that we ensure the char will be erased from the string //
{
str[j] = str[i];
j++;
}
}
str[j] = '\0'; //the end of the new string after the whole process//
}
char* input_long(void) //this function gets a string dynamically allocated//
{
char tempstr[80], *str;
printf("enter a string\n");
gets(tempstr);
str = (char*) malloc((strlen(tempstr) + 1) * sizeof(char));
strcpy(str, tempstr);
return str;
}
My code didnt run well; when I run it, it seemed to lead the statement which asks the user to enter a string. I repaired the code by adding _flushall() , and now the code is running well:
_flushall();
str=input_long();
printf("\nplease enter a char to be removed from the string: ");
scanf("%c", &ch);
I dont really understand why adding that statement indeed repaired it.