简体   繁体   中英

Error in c when iterating: use of undeclared identifier i

I am creating a program that will ask a command line argument from the user, and the user need to input only integers as the argv[1]. It should reject any input other than integers. My code is as below:

#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main(int argc, string argv[] )
string s = argv[1];
    for (int i = 0; n = strlen(s); i< n; i++)
    {
        if(!( isdigit(s[i])) )
        {
            printf("All numbers: correct input");
            return 1;
        }
    }

    //Else print a prompt asking for a plaintext to cipher
    else
    {
        string p = get_string("Your text here: ");
        return 0;
    }
    }

Running the above code throws me an error: error: use of undeclared identifier 'i' for (int i = 0; n = strlen(s); i< n; i++)

Where do I do wrong here and how do I fix this? Thanks.

Sorry if my questions seem stupid, I am still a newbie learning here and know absolutely nothing about C before. Thanks for the help though.

If you have a C89 compiler you will need to put the delarations at the top of the scope block, so the variable i has to be declared before the for loop.

Try this if your using C89:

#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main(int argc, string argv[] ){
 string s = argv[1];
 int i = 0;
 int n = strlen(s);
 for (; i< n; i++)
    {
        if(!( isdigit(s[i])) )
        {
            printf("All numbers: correct input");
            return 1;
        }
    }

    //Else print a prompt asking for a plaintext to cipher
    else
    {
        string p = get_string("Your text here: ");
        return 0;
    }
  } //end of for loop?  TODO: fix your braces spacing the sample was broken
}//end of for main?  TODO: fix your braces spacing the sample was broken

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM