簡體   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