Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all 0's with 5's in a given number using sprintf and sscanf

Tags:

c++

c

printf

scanf

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 :)

like image 223
Mohamed Sharief Avatar asked Dec 23 '22 23:12

Mohamed Sharief


1 Answers

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.

like image 83
Blaze Avatar answered Dec 28 '22 07:12

Blaze