从文件中读取字符串并转换为 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()
给出)写入为 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
我注意到 VLA(可变长度数组)在 C++11 及更高版本中不受支持,因此应将行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()]);
相关文章:
- EASTL矢量<向量<int>>连续的
- 如何打印大于"无符号长长"的"std::bitset"的十进制值?
- 关于 std::bitset 构造函数的几个问题?
- 如何以滑动窗口方式从 std::bitset 读取位并将它们转换为 int?
- 在哪里可以找到 std::bitset 的数据成员?
- 对于std::bitset,是否有一个ffs()等价物
- 移动 std::bitset<N> 是否超过 N 个位置未定义的行为?
- 是否可以让 Bitset 将位打印到一行?
- 找不到使用 bitset 实例化模板函数的有效方法
- 我正在使用 std::bitset 并尝试创建两个大小为 100,000,000,000 的数组 std::bitset
- OMNeT++ cPacket as std::bitset 以应用 Reed-Solomon 编码
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 如何在<N>不发生内存泄漏的情况下同时(线程安全)填充 c++11 std::map<std::string,std::bitset*>?
- 初始化一对(bitset,int)的向量
- C 字符串比较“祝您好运”&gt;“再见”
- 将字符数组转换为 std::string 以传递到 std::bitset seg 错误
- std::bitset 哈希函数算法
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 与STD :: BITSET的工会成员的结构填充
- 从文件中读取字符串并转换为 bitset<12>