Home > Net >  How can I use a variable that is declared inside of an for loop when I'm outside of the loop?
How can I use a variable that is declared inside of an for loop when I'm outside of the loop?

Time:07-19

I am learning C and I need a help here. I'm just working on a little program from my course's exercise, and I need to use my variable (that is inside of an for loop) outside of the loop. I know its a very dumb question, but I need your help. Here's the code I wrote, in the CS50 IDE:

#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <ctype.h>
#include <string.h>

int main(void)
{
    // Verifies if the card_number is between 13 and 16 digits
    long card_number = 0;
    for (int i = 0; i < 20; i  )
    {
        card_number = get_long("Insert the card's number: ");
        int reach_zero = 0; 
        int digit_count = 0; 
        do
        {
            reach_zero = (card_number /= 10);
            digit_count  ;
        }
        while (reach_zero != 0); 
        if (digit_count >= 13 && digit_count <= 16)
        {
            break; 
        }
    }
    // Prints the card_number 
    printf("%li\n", card_number);
}

I just need to printf the card_number.

CodePudding user response:

If I have understood the question then just write

    card_number = get_long("Insert the card's number: ");
    long reach_zero = card_number; 
    int digit_count = 0; 
    do
    {
        reach_zero /= 10;
        digit_count  ;
    }
    while (reach_zero != 0); 

CodePudding user response:

Thank you all!!! Especially thanks to @Weather Vane. I took a look on the processto use strings in this case, and realized that I could just use sprintf and, after some readings on StackOverflow, I rewrote the code, now its good. Thanks!!

  • Related