I wrote a program to replace a letter in a string. Although it has no error, the output is not as expected. Please help me with it.
void replace(char s,char d);
printf("enter the string\n:");
printf("enter the the letter to be replaced\n:");
printf("enter the letter to be replaced with\n:");
void replace(char s, char d)
for (i = 0; a[i] != '\0'; i++)
if (a[i] == s)
a[i] = d;
f = 1;
if (f == 0)
printf("letter not found");
enter the string
:hello every one
enter the the letter to be replaced
enter the letter to be replaced with
:letter not found
while ( getchar() != '\n' )
scanf() function skips over initial whitespace characters when you read in strings using the
%s specifier, but it does not do this when your read
chars with the
%c specifier. The
gets() function that you use (which you should never ever ever use ever) reads through the newline, and discards it. So your first call to
scanf() has a clean input stream. When you call
scanf() the first time, a value is read into the variable
b, but the trailing newline is left behind in the input stream. Then, when you try to read the next value,
scanf() picks up this newline, instead of the value that you want to enter.
One fix for this is to discard any unwanted characters from the input stream like this:
while (getchar() != '\n') continue; // discard unwanted characters
You can also test for the
EOF character in the conditional expression if you really want to be careful. One virtue of this approach is that, no matter how many characters the user enters at your second prompt, only the first is taken, and the remaining characters through the newline are discarded. Since there is nothing left in the input stream,
scanf() has to wait for the user to enter something at your third prompt. You should place this code after each call to
scanf() to make sure that the input stream is clear.
gets() is a terrible and unsafe function begging for buffer overflows, because it doesn't check to see if there is enough memory allocated for the string it is getting. Instead, use
fgets(). This function takes an argument that specifies the maximum number of characters to read, including the null-terminator.
fgets() also reads the newline character into the string, so you have to dispose of that yourself if you don't want it. Here are the modifications you need to make:
int i = 0; ... char b,r; printf("enter the string\n:"); fgets(a, 100, stdin); while(a[i] != '\n' && a[i] != '\0') // remove newline ++i; a[i] = '\0'; printf("enter the the letter to be replaced\n:"); scanf("%c", &b); while (getchar() != '\n') continue; // discard unwanted characters printf("enter the letter to be replaced with\n:"); scanf("%c", &r); while (getchar() != '\n') continue; // discard unwanted characters replace(b,r); printf("%s\n", a); ...
I added a final
printf() to display the changed string.