在 C++ 中将 ASCII 代码构建为二进制代码,反之亦然,并且 运行 出现奇怪的错误

Building a code for ASCII to binary vice versa in C++ and running into a weird error

我正在构建一个程序,将 ASCII 转换为二进制,然后将二进制转换为 ASCII。到目前为止,我已经做了一些事情,逻辑似乎很合理,但是每次我尝试编译它时 运行 都会出错。错误是 "Binary_reverse' was not declared in this scope"。我试过四处寻找答案,但找不到任何东西。下面是我的代码。当我试图将它从终端粘贴到这里时,一些格式可能已经搞砸了。

#include <iostream> 
#include <fstream> 
#include <cmath> 
#include <stdlib.h> using namespace std;

void A_to_B(const char*);

void B_to_A(const char*);

int main(void) {

  cout <<"ASCII/BINARY Converter" << endl;

  cout <<"============================ \n \n" << endl;
 char response;

  char garbage[50];

  cout <<"1. ASCII to Binary converter" << endl;

  cout <<"2. Binary to ASCII Converter" << endl;

  while(response !='1' && response !='2' && response !='N' && response !='n') {

    cout <<"\n Enter \"1\" or \"2\" to specify task. Enter \"N\" to quit: ";

    cin >> response;

    cin.getline(garbage, 50);

    if(response !='1' && response !='2' && response !='N' && response !='n') cout <<"The value you entered was invalid. Please try again" << endl;

  }

  if(response=='N' || response=='n') {

    cout <<"User cancel" << endl;

    exit(0);

  }

  char text[501];

  cout <<"Enter the text/code you want to convert: ";

  cin >> text;

  if(response=='1') {

    A_to_B(text);

  }

  else {

    B_to_A(text);

  }

  cout <<"Conversion finished" << endl;

  return 0;

}

void A_to_B(const char* input) {

  int ascii;

  int length=strlen(input);

  cout <<" ";

  for(int x=0;

  x < length;

  x++) {

    ascii=input[x] char* binary_reverse=new char [9];

    char* binary=new char [9];

    int y=0;

    while(ascii !=1) {

      if(ascii % 2==0) {

        binary_reverse[y]='0';

      }

      else if(ascii % 2==1) {

        binary_reverse[y]='1';

      }

      ascii /=2;

      y++;

    }

    if(ascii==1) {

      binary_reverse[y]='1';

      y++;

    }

    if(y < 8) {

      for(;

      y < 8;

      y++) {

        binary_reverse[y]='0';

      }

    }

    for(int z=0;

    z < 8;

    z++) {

      binary[z]=binary_reverse[7-z];

    }

    cout << binary;

    delete [] binary_reverse;

    delete [] binary;

  }

  cout << endl;

}

void B_to_A(const char* input) {

  int length=strlen(input);

  int binary[8];

  int asciiNum=0;

  char ascii;

  cout <<" ";

  int z=0;

  for(int x=0;

  x < length / 8;

  x++) {

    for(int a=0;

    a < 8;

    a++) {

      binary[a]=(int) input[z] -48;

      z++;

    }

    int power[8];

    int counter=7;

    for(int x=0;

    x < 8;

    x++) {

      power[x]=counter;

      counter--;

    }

    for(int y=0;

    y < 8;

    y++) {

      double a=binary[y];

      asciiNum +=a* pow(2, b);

    }

    ascii=asciiNum;

    asciiNum=0;

    cout << ascii;

     }
  }

这是两条语句,您需要在这两条语句之间使用分号。

ascii=input[x] char* binary_reverse=new char [9];

类似于:

ascii=input[x];
char* binary_reverse=new char [9];