我是一名C++學生,致力於使用簡單密碼接收和編碼消息的項目。爲此,程序將每個單詞接受爲一個字符串,將該字符串轉換爲一個字符向量,然後在將每個字符存儲到一個文件中之前對其進行修改。在將編碼消息返回給主函數的行中,我收到此錯誤消息:<無法轉換std::vector<char, std::allocator<char> >' to
char *'爲參數1' to
char * cipher(char *,int)'。儘管有這個錯誤,程序仍然會運行,但是,只要輸入一個單詞並結束程序,程序就會停止。這是我正在使用的代碼:將std :: vector轉換爲char *
// Cipher.cpp
// This program accepts a message and encodes it
// Written by Will Grindle
#include<iostream.h>
#include<string.h>
#include<iomanip.h>
#include<math.h>
#include<fstream.h>
#include<vector.h>
using namespace std;
string get_message(); // function prototypes
char* cipher(char broken[], int length);
int main()
{
int index, length; // declare index for vectors
string message; // declare string
ofstream outfile; // declare filestream
outfile.open("MESSAGE.DAT", ios::in); // create file and open it
message = get_message(); // use function to retrieve data
length = message.length(); // find length of message
// declare vector for breaking the strings down
vector <char> broken(message.begin(), message.end());
vector <char> encoded(50); // declare vector for encoded message
encoded[index] = cipher(broken, length); // initialize encoded to new message
for(index = 0; index <= length - 1; index++)// loop for displaying values
{
cout << encoded[index] << endl;
}
if(outfile) // if there is no error with the file
{
for(index = 0; index <= length - 1; index++) // loop for writing encoded
{ // message to file
outfile << encoded[index] << endl;
cout << "Data written to file." << endl;
}
}
else
{
cout << "Error opening file." << endl;
}
outfile.close(); // close file
system("pause");
return 0;
}
string get_message()
{
string entry; // declare string
cout << "Please enter the word to be entered." << endl; // request entry
cin >> entry; // user enters word
system ("pause");
return entry;
}
char* cipher(char broken[], int length)
{
char index; // declare index
if(broken[index] < 123 && broken[index] > 96) // if characters are lowercase,
{ // make them uppercase
broken = broken - 32;
}
for(index = 0; index <= length - 1; index ++)
{
broken[index] = broken[index] * (2/3);
broken[index] = broken[index] - 12;
broken[index] = broken[index]^2;
}
cout << "Message encoded." << endl;
system ("pause");
return(broken);
}
我很樂意提供關於如何使這項工作的任何建議。謝謝!
嘗試使用char數組,動態分配,因爲您不知道它在編譯時的大小,而不是'vector'您傳遞給'cypher'(稱爲破壞)的第一個參數。這讓我覺得它看起來真的很像作業 –
arainone
'#include'???你使用什麼編譯器? –
在'cypher'中你可以使用'char index'而不需要設置任何值。這將導致未定義的行爲。 – NathanOliver