修剪字符串的最后一个字母

Pyt*_*ser 0 c++

假设我有一个分配给字符串变量的文本文件“myfile.txt”,我想删除点和扩展文件字符的其余部分.txt

#include <stdio.h>
#include <string>
#incldue <iostream>
    
int main() {

    std::string F = "myfile.txt";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

所以我想要实现的输出是“myfile”。使用 std::size 看起来并不适用于我的情况,有没有办法可以构建我想要的东西?

Ted*_*gmo 5

当您处理路径时,使用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"
}
Run Code Online (Sandbox Code Playgroud)

或者如果您希望将其返回为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
}
Run Code Online (Sandbox Code Playgroud)

(或使用wohlstadsreplace_extension答案