【问题标题】:C++ declaring Caesar CipherC++ 声明凯撒密码
【发布时间】:2013-08-02 01:14:40
【问题描述】:

编译时出现以下错误...

错误:“文本”未在此范围内声明

错误:“strlen”未在此范围内声明

如何通过声明它们来修复此错误...?

是我的代码遵循凯撒密码规则...

如何改进此代码以使其更高效???

程序将输入包含凯撒密码的文件, 并将解密代码以另一个文本输出...

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <math.h>
#include <stdio.h>
#include <string>
#include <string.h>
using namespace std;

int main()

{

    // Declarations

    string reply;

    string inputFileName;

    ifstream inputFile;

    char character;



    cout << "Input file name: ";

    getline(cin, inputFileName);



    // Open the input file.

    inputFile.open(inputFileName.c_str());     
    // Check the file opened successfully.

    if ( ! inputFile.is_open()) {

        cout << "Unable to open input file." << endl;

        cout << "Press enter to continue...";

        getline(cin, reply);

        return 1;


    }

    // This section reads and echo's the file one character (byte) at a time.

    while (inputFile.peek() != EOF) {

        inputFile.get(character);

        //cout << character;
    //Don't display the file...

    char cipher[sizeof(character)];


    //Caesar Cipher code...
    int shift;
    do {
        cout << "enter a value between 1-26 to encrypt the text: ";
        cin >> shift;
       } 
    while ((shift <1) || (shift >26));

    int size = strlen(character);
    int i=0;

    for(i=0; i<size; i++)
    {
        cipher[i] = character[i];
        if (islower(cipher[i])) {
            cipher[i] = (cipher[i]-'a'+shift)%26+'a';
        }
        else if (isupper(cipher[i])) {
            cipher[i] = (cipher[i]-'A'+shift)%26+'A';
        }
    }

    cipher[size] = '\0';
    cout << cipher << endl;


    }

    cout << "\nEnd of file reached\n" << endl;

    // Close the input file stream

    inputFile.close();

    cout << "Press enter to continue...";

    getline(cin, reply);

    return 0;   

}

【问题讨论】:

  • 嗯,您使用的是一个从未声明过的名为text 的变量。错误消息对我来说看起来很清楚。对于strlen,包括string.hstdlib.h(注意&lt;string&gt;&lt;string.h&gt; 是两个不同的、基本上不相关的标头)。
  • 如果您没有告诉我们这个程序在做什么,我们如何提出改进建议?
  • @IgorTandetnik 你能告诉我在哪里声明“文本”变量吗?
  • @0x499602D2 我刚刚在程序中添加了一些评论...

标签: c++ debugging encryption


【解决方案1】:

变量text 从未被声明过。您可以使用char* 或者更方便的std::string 并使用其成员函数c_str() 传递给strlen。 (除了你可以使用字符串的size() 成员函数)

Strlen 是&lt;cstring&gt; 的一部分

#include <cstring>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 2020-05-31
    • 2014-02-06
    相关资源
    最近更新 更多