C++将带有\ 0的字符串拆分为列表

Dra*_*yke 3 c++ split list delimiter

我想列出逻辑驱动器:

const size_t BUFSIZE = 100;
char buffer[ BUFSIZE ];
memset(buffer,0,BUFSIZE);

//get available drives
DWORD drives = GetLogicalDriveStringsA(BUFSIZE,static_cast<LPSTR>(buffer));
Run Code Online (Sandbox Code Playgroud)

然后缓冲区包含: 'C',':','\','0'
GetLogicalDriveStringA()之后的缓冲区
现在我希望填充List "C:\","D:\"依此类推.所以我试过这样的事情:

std::string tmp(buffer,BUFSIZE);//to split this string then
QStringList drivesList = QString::fromStdString(tmp).split("\0");
Run Code Online (Sandbox Code Playgroud)

但它没有奏效.甚至可以用分隔符分割\0?或者有没有办法按长度分割?

Som*_*ude 5

问题String::fromStdString(tmp)是它只会从缓冲区中第一个以零终止的"条目"创建一个字符串,因为这就是标准字符串的工作原理.这肯定是可能的,但你必须自己手动完成.

您可以通过查找第一个零,提取子字符串,然后在循环中直到找到两个连续的零来执行此操作,并执行相同的操作.

Pseudoish代码:

current_position = buffer;
while (*current_position != '\0')
{
    end_position = current_position + strlen(current_position);
    // The text between current_position and end_position is the sub-string
    // Extract it and add to list
    current_position = end_position + 1;
}
Run Code Online (Sandbox Code Playgroud)