在C++中将字符数组转换为字符串[已关闭]

5jvtdoz2  于 2023-03-14  发布在  其他
关注(0)|答案(2)|浏览(97)

已关闭。此问题需要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;
}
}
ttp71kqs

ttp71kqs1#

std::string具有接受单个const char*作为参数的构造函数。此构造函数未标记为explicit,因此它可用于隐式转换,就像此处在调用str2bin时发生的那样。
然而,构造函数并没有按照你想要的方式运行。构造函数假设const char*参数指向一个以null结尾的字节串。然而,你的buffer不是以null结尾的,所以如果你不从文件中读取null字节,这将导致缓冲区溢出和未定义的行为。
使用接受size作为附加参数的std::string构造函数,或者更好的是,从一开始就使用std::string,因为std::cout << buffer将导致相同的未定义行为:

std::string buffer(8, '\0');

//...

while (file.read(buffer.data(), 8))
{
    key = str2bin(buffer);
    outFile << buffer;
}
jucafojl

jucafojl2#

char buffer[8]隐式衰减为char*,并且std::string具有接受指向空终止char*数组的指针的构造函数。
因此,只要缓冲区以空结尾,代码就可以工作,您是否确保?即,最多是第八个字符'\0'?如果不是,您可能更喜欢:

std::string(std::begin(buffer),std::end(buffer));

std::string(buffer,std::size(buffer));

无论如何,我会建议在istream::read() call上阅读。

相关问题