未定义标识符/未声明

问题描述 投票:1回答:2

我最近启动了C ++,我想创建一个可以调用的简单终止密码函数,但是由于我从python程序复制了编码结构,因此似乎收到4个错误和2个警告。模式位是布尔值,其中true表示加密,false表示解密(它在python上起作用,所以嘿):)。

我创建“ int”所在函数的第一行,它说的是“ indefined”(未定义)“ identifier”

同一行中的第二个说“期望为')'”

第三个是在3条if语句之后,即使定义了,也说“ identifier” CharPos“ undefined”

在同一行上,Forth说“'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;
}

任何帮助将不胜感激

c++ caesar-cipher
2个回答
0
投票

您对某些变量的范围存在一些问题,例如:char CharPos2 = CharPos; charPos不在范围内,因此实际上是无效的赋值。

因此,不要在其他每个if中都定义一个新的CharPost,而是先声明它,然后在每个if中重新分配它,例如:

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;
}

0
投票

如上所述,您的代码中的主要问题是在每个CharPos子句中都重新定义了if

在每个地方放置int CharPos = ...的地方,都会创建一个new变量,即使它的名称与您相似,但对于编译器来说,此名称有三个unique变量。为了在所有scopes-变量环境中使用相同的变量,您应该在所有的第一个公共范围内定义once,即在[C0 ] [for子句之前的循环。

此外,如上所述if - else等效于Mode != true || Mode != false

为了安全起见,我重写了您的代码,实现了所需的加密,并且更具可读性(IMO)。

true
© www.soinside.com 2019 - 2024. All rights reserved.