假设我有一个分配给字符串变量的文本文件“myfile.txt”,我想删除点和扩展文件字符的其余部分.txt
#include <stdio.h>
#include <string>
#incldue <iostream>
    
int main() {
    std::string F = "myfile.txt";
    return 0;
}
所以我想要实现的输出是“myfile”。使用 std::size 看起来并不适用于我的情况,有没有办法可以构建我想要的东西?
当您处理路径时,使用std::filesystem会很有帮助。
#include <filesystem>
#include <string>
#include <iostream>
int main() {
    std::string F = "myfile.txt";
    std::filesystem::path p(F);
    std::cout << p.stem();                         // prints "myfile"
}
或者如果您希望将其返回为string:
#include <string>
#include <iostream>
#include <filesystem>
int main() {
    std::string F = "myfile.txt";
    F = std::filesystem::path(F).stem().string(); 
    std::cout << F << '\n';                       // prints myfile
}
(或使用wohlstadsreplace_extension的答案)
| 归档时间: | 
 | 
| 查看次数: | 133 次 | 
| 最近记录: |