【问题标题】:removing a word from a char array从 char 数组中删除一个单词
【发布时间】:2019-04-26 18:40:50
【问题描述】:

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

C:\用户\微 电容器\源\repos\FlatApoc\x64\Debug\FlatApoc.exe/Images/Play1.png

我要解决的问题是摆脱

FlatApoc.exe

来自 char 数组。我已经知道了

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);

【问题讨论】:

  • 使用std::string 或许std::regex 会使这种方式更容易。
  • 另外boost filesystemstd::filesystem 的最新标准添加将使您的手指剪断一样简单。 (更不用说一些可以用来提取完整​​文件路径的目录部分的基本 WinAPI 函数)
  • 你为什么写 C 却标记问题 C++?

标签: c++ arrays char


【解决方案1】:

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;
}

Live demo

【讨论】:

    【解决方案2】:

    Nvm。我现在修复了它,但我将代码留在这里:

    char path[MAX_PATH]; // The path of the executable
    GetModuleFileName(NULL, path, sizeof(path)); // Get the path
    char search[] = "\\FlatApoc.exe"; // The programs name
    char *ptr = strstr(path, search);
    *ptr = NULL;
    
    char pathbuff[256]; // Buffer for the png file
    strncpy_s(pathbuff, path, sizeof(pathbuff));
    strncat_s(pathbuff, "/Images/Play1.png", sizeof(pathbuff)); // "/Images/Play1.png" was the link from the executables folder
    Button_Play1 = IMG_Load(pathbuff); // Load image
    

    【讨论】:

      猜你喜欢
      • 2013-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 2017-04-06
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      相关资源
      最近更新 更多