首页 > 解决方案 > 错误:从 'char' 到 'const char' 的无效转换 [-fpermissive] strcat(encrypted, key[i]);

问题描述

为什么 strcat() 函数不起作用。错误是从 'char' 到 'const char' 的无效转换。为什么错误显示 const char。我没有将任何数组声明为 const。

#include<iostream>
#include<cstring>
using namespace std;
int main(){
  cout<<"Enter the secret message"<<endl;
  char secret[80]{};//Initialising leads to removal of garbage values
  cin.getline(secret,80);
  char alphabet[] {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
  char key[] {"XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"};
  int i{};
  char encrypted[80] {};
  char decrypted[80] {};

  for(auto val:secret){
    i=0;
    while(i<strlen(alphabet) && val!=alphabet[i]){
      i++;
    }
    if(i<strlen(alphabet))
      strcat(encrypted, key[i]);
    else
      strcat(encrypted, val);
  }
  cout<<"Encrypting..."<<endl;
  cout<<"Encrypted value: "<<encrypted;

  for(auto val: encrypted){
    i=0;
    while(i<strlen(encrypted) && val!=encrypted[i])
      i++;
    if(i<strlen(encrypted))
      strcat(decrypted, alphabet[i]);
    else
      strcat(decrypted, val);
  }
  cout<<"Decrypting: "<<endl;
  cout<<"Decrypted value: "<<decrypted<<endl;
  return 0;
}

标签: c++

解决方案


strcat函数将一个字符串连接到另一个字符串。但key[i]不是字符串。


推荐阅读