CS50“期望的表达式”用于C中的else语句?

时间:2018-10-25 19:12:23

标签: c cs50

我似乎找不到我最后一个错误的原因。遗憾的是,我没有任何急需帮助的现实生活中的开发人员朋友,因此发布此帖子是我唯一的选择。

给出

错误是 57:13:错误:预期表达             其他             ^

有人可以检查我的代码并向我提示问题吗?

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

int main(int argc, string argv[])
{
    // make sure command line input correct.
    if (argc != 2)
    {
        printf("Command line arguments can't be greater or lower then 2\n");
        return 1;
    }

    // get a valid key = key
    string key = (argv[1]);
    int lengthK = strlen(key);
    for (int i = 0; i < lengthK; i++)
    {
        if (!isalpha(key))
            printf("Key must be alphabetical \n");
        return 1;
    }

    //get plaintext
    string(plaintext) = get_string("Plaintext : ");

    //convert plaintext and keeping upper/lowercase in mind
    int i;
    int lengthP;
    int index;

    printf("ciphertext: ");
    for (i = 0, index = 0, lengthP = strlen(plaintext); i < lengthP; i++)
    {
        if (isalpha(plaintext[i]))
        {
            //change uppercase letters
            if (isupper(plaintext[i]))
            {
                printf("%c", (((plaintext[i] - 'A') + toupper(key[index]) - 'A') % 26) + 'A');
            }

            //change lowercase letters
            if (islower(plaintext[i]))
            {
                printf("%c", (((plaintext[i] - 'a') + key[index] - 'A') % 26) + 'a');
            }
            index = (index + 1) % lengthK;
            //rest
            else
            {
                printf("%c", (plaintext[i]));
            }
        }
    }
    printf("\n");
}

2 个答案:

答案 0 :(得分:3)

这是因为您的语法无效。

您的书写方式就是这种方式

if (someConditions)
{
    /* do something */
}
someInstructions(); /* the if is now over since the curly brackets are closed and there was no else */

/* here is an else without if, which is a non sense */
else
{
    /* do something else */
}

你要么

  • 放错了该指令index = (index + 1) % lengthK;

  • 放错了if (isalpha(plaintext[i]))

  • 的大括号

答案 1 :(得分:0)

括号在错误的位置:

        if (isalpha(plaintext[i]))
        {
            ...
        index = (index + 1) % lengthK;

        //rest
        else
        {
            printf("%c", (plaintext[i]));
        }
        }    // <---- here

您需要将其移至else上方:

        if (isalpha(plaintext[i]))
        {
            ...
            index = (index + 1) % lengthK;
        }
        //rest
        else
        {
            printf("%c", (plaintext[i]));
        }