Home > Net >  How do i fix this error in c? declaration shadows a local variable
How do i fix this error in c? declaration shadows a local variable

Time:10-31

I am trying to get the number of cards the user wants to enter and ask the definition and term each time. I am wondering what I am doing wrong in the loop for nameofcards variable.

screenshot compiler warning

Thank you in advance


int main(int argc, string argv[])
{
    // check argc
    if (argc != 2)
    {
        // correct user
        printf("Usage: ./deck name\n");

        return 1;
    }
    else
    {
        // create loop to check user key
        for (int loop = 0, n=0; loop < n; loop  )
        {
            if (!isalpha(argv[1][loop]))
            {
                //correct user
                printf("Usage: ./deck name");

                return 1;
            }
        }
    }

    FILE *fp ;
    // open file
    fp = fopen(argv[1], "w");
    // make the file name as the user input in the command line
    scanf("%s", argv[1]);

    int numberofcards = scanf("How many cards(includes definition nad term) do you need: \n");
    for ( int i = 0, numberofcards; i < numberofcards ; i  )
    {
        printf("Term: \n");
        printf("Definition: \n");
    }

    // close file
    fclose(fp);

    return 0;
}

CodePudding user response:

The error is shown because you are redeclaring the numberofcatds variable in your for loop

Fix is to remove numberofcards in the variable declaration part of your for loop

for ( int i = 0, numberofcards; ...

should be

for ( int i = 0; ...

CodePudding user response:

In addition to the problem with the shadowed variable: scanf returns the number of converted values, i.e. 0 or 1, not the converted value(s).

You need something like

scanf("%i", &numberofcards);

plus error handling.

  •  Tags:  
  • c
  • Related