繁体   English   中英

从文件中读取字符串并转换为bitset <12>

[英]read string from file and turn into bitset<12>

嗨,我正在尝试从txt文件读取字符串,并将其转换为bitset <12>字符串形式的二进制文件。

int main()
{
using namespace std;

std::ifstream f("fruit.txt");
std::ofstream out("result.txt");

std::hash<std::string>hash_fn;

int words_in_file = 0;
std::string str;
while (f >> str){
    ++words_in_file;
    std::bitset<12>* bin_str = new std::bitset<12>[3000];
    int temp_hash[sizeof(f)];
    std::size_t str_hash = hash_fn(str);
    temp_hash[words_in_file] = (unsigned int)str_hash;
    bin_str[words_in_file] = std::bitset<12>((unsigned int)temp_hash[words_in_file]);
    out << bin_str[words_in_file] << endl;
    delete[] bin_str;
}
out.close();
}

但是有错误。 我该如何更改?

这是我编写的一些代码,可将输入文件"file.txt"转换为二进制文件。 它通过获取每个字符的ascii值并将其表示为二进制值来实现此目的,尽管我不确定如何在此处将bin_str写入文件。

#include <string>
#include <fstream>
#include <streambuf>
#include <bitset>
#include <iostream>

int main(){
    std::ifstream f("file.txt");
    std::string str((std::istreambuf_iterator<char>(f)),
                    std::istreambuf_iterator<char>());  // Load the file into the string
    std::bitset<12> bin_str[str.size()]; // Create an array of std::bitset that is the size of the string

    for (int i = 0; i < str.size(); i++) {
        bin_str[i] = std::bitset<12>((int) str[i]); // load the array
        std::cout << bin_str[i] << std::endl; // print for checking
    }
}

边注:

std::bitset<12>可能不是您想要的,如果您查看ascii字符,您可以拥有的最大数字是127,而二进制只有7位数字,所以我假设您想要的东西更像std::bitset<7>std::bitset<8>

编辑:

如果要将其写入文件,则需要使用std::ios::binary打开文件,然后遍历位集数组,并将它们的无符号长代表(从to_ulong()给出to_ulong()为const char。指针( (const char*)&ulong_bin )。 现在,当您使用二进制编辑器打开文件时,您会看到二进制写入和常规写入之间的区别,但是您会注意到像cat这样的程序仍可以将您编写的二进制文件解密为简单的ascii字母。

 std::ofstream out("file.bin", std::ios::binary); for (int i = 0; i < str.size(); i++) { unsigned long ulong_bin = bin_str[i].to_ulong(); out.write((const char*)&ulong_bin, sizeof(ulong_bin)); } 

编辑 :感谢@PeterT

引起我注意的是,C ++ 11及更高版本不支持VLA(可变长度数组),因此std::bitset<12> bin_str[str.size()];行不支持std::bitset<12> bin_str[str.size()]; 应该更改为以下之一:

 std::bitset<12> *bin_str = new std::bitset<12>[str.size()]; // make sure you delete it later // OR std::vector<std::bitset<12>> bin_str(str.size()); // OR std::unique_ptr<std::bitset<12>[]> str_ptr (new std::bitset<12>[str.size()]); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM