C++ SDL 2.0 - 使用循环导入多个纹理

标签 c++

我不知道这是否可行,但我已经在不同的语言中使用过这种技术,但在 C++ 中很难使用它。我有 10 张图像,我正尝试使用循环将它们加载到数组中:

for (int i = 0; i < 10; i++)
{
    Sprite[i] = IMG_LoadTexture(renderer, "Graphics/Player" + i + ".png");
}

但这似乎在 C++ 中不起作用,所以我想知道我做错了什么,或者我可以做些什么来获得相同的结果而不必像这样单独加载每个图像:

Sprite[0] = IMG_LoadTexture(renderer, "Graphics/Player0.png");

我的错误是:“表达式必须具有整数或无作用域的枚举类型”

感谢您的帮助 =)

最佳答案

你不能这样做:

"这是我的号码:"+ (int)4 + "!";

这是非法的。尝试使用 operator+ a const char* 和 const char[SOME_INT_GOES_HERE] 时会出错,或者尝试使用 operator+ 将 int 添加到字符串时会出错。事情不是那样的。

您必须使用 C(即 snprintf())或字符串流。这是我用于隔离问题的测试代码:

#include <iostream>
#include <string>

int main()
{
        int a = 1;
        std::string str = "blah";
        std::string end =  "!";

        //std::string hello = str + a + end;// GIVES AN ERROR for operator+
        std::string hello = "blah" + a + "!";
      
        //const char* c_str = "blah" + a + "end";
        //std::cout << c_str << std::endl;
        std::cout << hello << std::endl;
        return 0;
}

这是使用字符串流的替代解决方案。

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    int i = 0;
    std::string str;
    std::stringstream ss;
    
    while (i < 10)
    {
        //Send text to string stream.
        ss << "text" << i;
        
        //Set string to the text inside string stream
        str = ss.str();
        
        //Print out the string
        std::cout << str << std::endl;
        
        //ss.clear() doesn't work. Calling a constructor
        //for std::string() and setting ss.str(std::string())
        //will set the string stream to an empty string.
        ss.str(std::string());
        
        //Remember to increment the variable inside of while{}
        ++i;
    }
} 

或者,如果您使用的是 C++11(只需要 -std=c++11),您也可以使用 std::to_string(),但 std::to_string() 在某些情况下已损坏编译器集(即常规 MinGW)。要么切换到它工作的另一种风格(即 MinGW-w64),要么在幕后使用字符串流编写自己的 to_string() 函数。

snprintf() 可能是执行此类操作的最快方式,但为了更安全的 C++ 和更好的风格,建议您使用非 C 方式执行操作。

关于C++ SDL 2.0 - 使用循环导入多个纹理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29373712/

相关文章:

c++ - 双循环链表。新节点未插入。 C++

c++ - 如果我不先创建 TCP 连接,为什么发送数据报不起作用?

c++ - 关于这个在 Linux 上用 gcc 编译的程序中的 vtable,nm 告诉我什么?

c++ - 在 Ubuntu 上使用 wxWidgets2.9.3 出错

c++ - Direct3D 奇怪的崩溃

c++ - 成员与非成员运算符重载

c++ - 基于 CDialog 的 MFC 应用程序仅在主监视器中启动

c++ - 声明类实例的两种方式的区别

C++ std::function 运算符=

如果原型(prototype)是本地的,则使用流 I/O 的 C++ 类型约束将失败