Home > Enterprise >  In C, can i use scanf with just one %d input but get 2 variables with that same input?
In C, can i use scanf with just one %d input but get 2 variables with that same input?

Time:11-13

By the time i finish counting the digits(K) with a while/do loop, the original N number is lost and its now 0. So i cant rly go to step 4). Thats why i thought id create 2 variables with the same input so i can just do the 4) step as a seperate process entirely.

(CONTEXT basically the task is to make a program that 1) read a number N (1<=N<=999999999) with scanf, 2) if the number is out of mentioned bounds, make message "Wrong Input" appear, 3) make it count the digits of said number, (digits as K),
4) If N includes K as a digit, make message "Yes" appear, otherwise make "No" appear.)

int main()
{

    int K,N;

    scanf("%d", &N);
    if (N<=1 || N>=999999999)
    {
        printf("Wrong Input\n");
    }
    else
    {
        do
        {
            N=N/10;
            K  ;
        }
        while(N!=0);        
     }
    return 0;
}

CodePudding user response:

else
{
    int M = N;
    do
    {
        M=M/10;
        K  ;
    }
    while(M!=0);        
}

CodePudding user response:

You can just create a new local variable and store the value of N to be used later



#include <stdio.h>
int main() {
    // initializing with 0 because 0 = false and 1 = true, to use true or false you need the bool.h header file
    int containsDigit = 0;
    int K, N, digits = 0;
    scanf("%d", &N);
    K = N;
    if (N <= 1 || N >= 999999999) {
        printf("Wrong Input\n");
    } else {
        while (N != 0) {
            N /= 10;
            digits  ;
        }
        while(K != 0) {
            int cdigit = K % 10;
            if (cdigit == digits) {
                containsDigit = 1;
                break;
            }
            K /= 10;
        }

        if (containsDigit) printf("yes");
        else printf("No");
    }
    return 0;
}

  • Related