【发布时间】:2016-01-07 18:30:14
【问题描述】:
我是一名 C++ 学生,正在从事一个项目,以使用简单的密码接收和编码消息。为此,程序接受每个单词作为字符串,将字符串转换为字符向量,然后在将每个字符存储到文件之前对其进行修改。在将编码消息返回给主函数的行中,我收到以下错误消息: std::vector<char, std::allocator<char> >' tochar*' for argument 1' tochar* cipher(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);
}
我愿意接受有关如何完成这项工作的任何建议。谢谢!
【问题讨论】:
-
尝试使用一个 char 数组,因为您在编译时不知道它的大小而动态分配,而不是
vector<char>作为您传递给cypher的第一个参数(称为损坏)。这让我觉得它看起来真的像一个家庭作业???? -
#include <iostream.h>???你用的是什么编译器? -
在
cypher中,您使用char index;而无需设置值。这将导致未定义的行为。 -
我正在为一个我无法选择编译器的类做这个,所以这是在 Bloodshed Dev c++ 4 上。是的,我知道它已经过时了,但我真的没有选择.