简体   繁体   中英

Keep getting undeclared identifier I error caesar

I'm working on pset2 from the cs50 course, but I don't understand why I keep getting this error that I didn't declare I, because I think I did.. First I ask for a number to use as a key for the encrypting, than I ask for plain text, which should be encrypted by the number given, and printed out later.

Here's my code:

int main(int argc, string argv[])
{
    // get key from command line argument, return 1 if wrong
    if (argc < 2)
    {
        printf("No value entered!\n");
        return 1;
    }

    //store key in integer
    int k = atoi(argv[1]);

    if (k < 0)
    {
        printf("No right variable detected\n");
        return 1;
    }
    else
    {
        printf("Plain text: \n");
        string s = get_string();

        // iterate over strings in argv
        for (int i = 0; n = strlen(s); i < n; i++);
        {
            if (isalpha(s[i]))
            {
                // for capitalized letters
                if (isupper(s[i]))
                {
                    int a = s[i] - 65;
                    int b = (a + k) % 26;
                    int c = b + 65;
                    printf("%c", c);
                }

                //for lowercase
                else
                {
                    int d = s[i] - 97;
                    int e = (d + k) % 26;
                    int f = e + 97;
                    printf("%c", f);
                }
            }
            else
            {
                //for non alphabetical characters
                printf("%c", s[i]);
            }
        }
    }
    // print new line 
    printf("\n");
    return 0;
}

For loop is wrong, it accepts 3 parameters, you set it 4.

Also, notice semicolon after your for loop.

This line:

for (int i = 0; n = strlen(s); i < n; i++);

should be:

for (int i = 0, n = strlen(s); i < n; i++)

Notice comma and no semi-colon at the end

You have a ; at the end of for loop

for (int i = 0; n = strlen(s); i < n; i++);
                                          ^

Change it to

for (int i = 0, n = strlen(s); i < n; i++)

Moreover, as you can see init must be placed before the first semicolon , (comma) separated.

Side notes

  1. You should avoid to use "magic numbers" in code. In your case you can simply use
  2. You should use variable names that can make your code more readable
  3. You can do your ashing with a single variable, not 6

     if (isalpha(s[i])) { int ashed; // for capitalized letters if (isupper(s[i])) { ashed = s[i] - 'A'; ashed = (ashed + k) % 26; ashed += 'A'; } //for lowercase else { ashed = s[i] - 'a'; ashed = (ashed + k) % 26; ashed += 'a'; } printf("%c", ashed); } 

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