strtok()循环返回空白项,TreeControl出现多余空白文件夹问题
问题分析与解决
问题原因
你的代码逻辑存在漏洞:当strtok遍历完所有有效子文件夹后,再次调用strtok(NULL, ",")会返回NULL,但此时循环仍会执行InsertItem(dir, hItem),将NULL传入TreeControl,就会生成那个空白项。
修正后的代码
HTREEITEM hItem; HTREEITEM hsubItem; char line[] = "/Desktop/Songs,Pop,Country" ; char* dir= strtok(line,","); printf("%s\n", dir); hItem= treeview.InsertItem(dir); // 插入根目录 // 先获取下一个token,非空时再插入子节点 dir= strtok(NULL,","); while (dir!= NULL) { printf("%s\n", dir); hsubItem = treeview.InsertItem(dir, hItem); // 插入Pop、Country子节点 dir= strtok(NULL,","); }
逻辑说明
- 调整循环顺序:先调用
strtok获取下一个子文件夹路径,判断不为NULL时再执行插入操作 - 避免了
NULL值传入InsertItem,从根源上消除空白项
内容的提问来源于stack exchange,提问作者nicu98
相关产品推荐
相关产品推荐

