[英]Converting std::vector to char*
我是一名從事項目研究的c ++學生,它使用簡單的密碼來接收和編碼消息。 為此,該程序接受每個單詞作為字符串,將字符串轉換為字符向量,然后修改每個字符,然后再將其存儲在文件中。 在將編碼后的消息返回到主函數的行中,我收到以下錯誤消息:<無法將std::vector<char, std::allocator<char> >' to
char *',參數1' to
char *密碼(char *,int)'。 盡管出現此錯誤,程序仍將運行,但是,它會在輸入一個單詞后立即停止並結束程序。 這是我正在使用的代碼:
// 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);
}
我願意就如何進行這項工作提出任何建議。 謝謝!
在C ++中,向量實際上不是char數組,因此您不能將其傳遞給需要char數組的函數。 您在這里有一些選擇。
首先,我建議您更新代碼,以使cipher函數將向量或std :: string作為參數。 這些對象比原始數組更安全,因為它們知道它們的大小,並且可以根據需要進行重新分配。
其次,您可以更改對cipher的調用,以傳遞指向向量基礎數組的指針,如下所示:
cipher(broken.data(), broken.size());
我認為這是一個不太優雅且更容易出錯的解決方案,但是如果您願意,歡迎使用它。
您的代碼看起來更像C ...
這似乎也很不錯: C和C ++之間的差異它還指出了有關樣式的一些內容以及您可以做但不應該做的事情。
當然還有這個Programmers.StackExChange帖子: C和C ++之間的根本區別是什么?
嘗試使用現代的C ++ IDE,例如CodeBlocks,Eclipse,Netbeans等。 這將幫助您從一開始就預防某些故障。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.