首页 > 解决方案 > 从 char 数组中删除一个单词

问题描述

我要将图像放到我的 sdl 应用程序中,为此我需要知道它的路径。当我将完整路径放入IMG_Load()函数时,它会起作用。当我尝试使用 windows.h 函数GetModuleFileName()并将其与另一个字符数组结合时,我得到:

C:\Users\微电容\source\repos\FlatApoc\x64\Debug\FlatApoc.exe/Images/Play1.png

我要解决的问题是摆脱

FlatApoc.exe

从字符数组。我已经知道

FlatApoc.exe

来自GetModuleFileName(). 解决此问题的解决方案只是从 char 数组中删除 FlatApoc.exe,但我对 c++ 很陌生,我不知道如何执行这样的功能。

我的代码是:

char path[MAX_PATH]; // The path of the executable
GetModuleFileName(NULL, path, sizeof(path)); // Get the path
char pathbuff[256]; // Buffer for the png file
strncpy_s(pathbuff, path, sizeof(pathbuff));
strncat_s(pathbuff, "/Images/Play1.png", sizeof(pathbuff));
Button_Play1 = IMG_Load(pathbuff);

标签: c++arrayschar

解决方案


C++ 方式。请注意它看起来多么自然:

#include <windows.h>
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    char path [MAX_PATH];
    GetModuleFileName (NULL, path, sizeof (path));
    std::string s = path;
    auto n = s.rfind ('\\');
    s.erase (n);
    s += "/Images/Play1.png";
    std::cout << s;
}

现场演示


推荐阅读