I am trying to replace all the 0's present in a given integer with 5's.
To do that i am using sprintf to convert integer to string and do the operations on the string and finally convert back the string into an integer
Below is the code:
#include<stdio.h>
int main() {
int num=0, i=0;
char str[10];
printf("Enter the number: ");
scanf("%d",&num);
sprintf(str,"%d",num);
printf("string str:%s",str);
while(str[i]!='\0')
{
if(str[i]==0)
str[i]=5;
i++;
}
sscanf(str,"%d",&num);
printf("\nBefore replacement: %s", str);
printf("\nAfter replacement: %d", num);
}
I am getting wrong output
Could someone identify and correct what is wrong here. Thanks :)
scanf("%d", num);
should be scanf("%d", &num);
.
Also, this here
if (str[i] == 0)
str[i] = 5;
should be
if (str[i] == '0')
str[i] = '5';
Because 0
is just the same as '\0'
, but you want to replace the character representing 0
.
Also, in your output, you got before and after mixed up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With