已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。
昨天关门了。
Improve this question
我有下面的代码。buffer
是一个字符数组。我没有把buffer
转换成字符串,但是当我调用str2bin
函数时代码仍然有效。你能帮我解释一下吗?
#include <winsock2.h>
#include <iostream>
#include <fstream>
#include <cstring>
#include <bits/stdc++.h>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
string str2bin(string s)
{
string bin = "";
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '#')
{
bin += "00000000";
}
else
{
char c = s[i];
bitset<8> b(c);
bin += b.to_string();
}
}
return bin;
}
void encryptFile(string keyFile, string ptFile)
{
string pt, key;
char buffer[8];
ifstream file(keyFile, ios::binary);
ofstream outFile("ciphertext.txt", ios::binary);
if (!file.is_open())
{
cout << "Error opening key file.\n";
return "0";
}
while (file.read(buffer, 8))
{
key = str2bin(buffer);
outFile << buffer;
}
file.close();
}
int main()
{
encryptFile("key.txt", "plaintext.txt");
return 0;
}
}
2条答案
按热度按时间ttp71kqs1#
std::string
具有接受单个const char*
作为参数的构造函数。此构造函数未标记为explicit
,因此它可用于隐式转换,就像此处在调用str2bin
时发生的那样。然而,构造函数并没有按照你想要的方式运行。构造函数假设
const char*
参数指向一个以null结尾的字节串。然而,你的buffer
不是以null结尾的,所以如果你不从文件中读取null字节,这将导致缓冲区溢出和未定义的行为。使用接受size作为附加参数的
std::string
构造函数,或者更好的是,从一开始就使用std::string
,因为std::cout << buffer
将导致相同的未定义行为:jucafojl2#
char buffer[8]
隐式衰减为char*
,并且std::string
具有接受指向空终止char*
数组的指针的构造函数。因此,只要缓冲区以空结尾,代码就可以工作,您是否确保?即,最多是第八个字符
'\0'
?如果不是,您可能更喜欢:或
无论如何,我会建议在istream::read() call上阅读。