提问者:小点点

未定义的标识符/未声明


我最近刚开始使用C++,我想创建一个可以调用的简单的ceaser密码函数,但是由于我复制了python程序的编码结构,我似乎收到了4个错误和2个警告。 模式位是一个bool,其中true表示加密,false表示解密(这在python上很有效,所以嘿):)。

在我创建函数的第一行,其中“int”是,它在“undefined”中表示“identifier”

在同一行中的第二个写着“应为')'”

第三个是在3个if语句之后,将“identifier”表示为“undefined”,即使它是定义的

然后在同一行上说“'charpos':未声明的标识符”

#include <iostream>
#include <fstream>
#include <string>

std::string Encryption(std::string Password, int Key, bool Mode) {
    std::string Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
    std::string EncryptPass = "";
    if (Key > 94) {
        Key = Key % 94;
    }
    for (int X = 0; X < Password.length(); X++) {
        if (Password.at(X) == ' ') {
            EncryptPass = EncryptPass + " ";
        }
        else {
            for (int Y = 0; Y < 94; Y++) {
                if (Password.at(X) == Alphabet.at(Y)) {
                    if (Mode == true) {
                        int CharPos = Y + Key;
                        if (CharPos > 93) {
                            CharPos = CharPos - 94;
                        }
                    }
                    if (Mode == false) {
                        int CharPos = Y - Key;
                        if (CharPos < 0) {
                            CharPos = CharPos + 94;
                        }
                    }
                    if (Mode != true or Mode != false) {
                        int CharPos = 0;
                    }
                    char CharPos2 = CharPos;
                    char EncryptChar = Alphabet.at(CharPos2);
                    EncryptPass = EncryptPass + EncryptChar;
                }
            }
        }
    }
    return EncryptPass;
}

如有任何帮助,将不胜感激


共1个答案

匿名用户

您对某些变量的作用域有一些问题,例如:char CharPos2=charpos;charpos不再在作用域中,因此实际上是一个无效的赋值。

因此,不是在every if else中定义新的CharPost,而是在every if check中声明它并重新分配它,如:

if (Password.at(X) == Alphabet.at(Y)) {
    int CharPos = 0;
    if (Mode == true) {
        CharPos = Y + Key;
        if (CharPos > 93) {
            CharPos = CharPos - 94;
        }
    }
    if (Mode == false) {
        CharPos = Y - Key;
        if (CharPos < 0) {
            CharPos = CharPos + 94;
        }
    }
    if (Mode != true or Mode != false) {
        CharPos = 0;
    }
    char CharPos2 = CharPos;
    char EncryptChar = Alphabet.at(CharPos2);
    EncryptPass = EncryptPass + EncryptChar;
}