我有一个二进制文件 text.bin
。里面的文字是这样写的:
4helo5hello6hello
。如果我不知道里面有 3 根弦,
我怎么知道?我想从一个动态的字符串数组
二进制文件,但首先我必须知道文件中有多少个字符串。
我知道我可以这样读:
ifstream dat("text.bin", ios_base::binary);
if (!dat)
{
cout << "Error";
return 1;
}
int temporary;
dat.read((char*)(&temporary), sizeof(temporary));
char *arrray = new char[temporary];
dat.read(arrray, temporary);
string word = string(arrray, temporary);
我如何将它变成一个循环,以便只要二进制文件中有要读取的内容,它就会读取?我如何找出有多少个单词,以便为这些单词准备一个动态数组?我正在使用:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
最佳答案
保持简单。如果二进制格式像你说的那样:例如 4helo5hello6hello,请执行以下操作;
读取第一个数字,
从第一个数字的位置到字符串的长度(您读取的数字)的子字符串,
将子串放入二维数组(一维为字符串个数,另一维为字符串长度),
重复清洗漂洗,直到到达文件末尾。
数组第一维的长度为文件中字符串的个数。该数组现在包含读取文件中的所有字符串。
干杯!
关于c++ - 如何找出二进制文件中写入了多少个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35177998/