如何添加一个数字到一个字符串

How to i add a number to a string?

本文关键字:一个 字符串 数字 何添加 添加      更新时间:2023-10-16

我想做这样的事情(显示我在SDL游戏中运行的FPS):

SDL_WM_SetCaption("FPS: " + GetTicks(&fps)/1000.f, NULL);

但是Visual Studio智能提示表达式必须是整型或枚举类型。

我做错了什么?

如果这真的是c++,请考虑流;

std::ostringstream str;    
str << "FPS: " << GetTicks(&fps)/1000.;    
SDL_WM_SetCaption(str.str().c_str(), NULL);

C不支持简单类型(如intfloat)到更复杂类型(如字符串)的转换。

您应该检查sprintf功能:

char buffer[64];
sprintf("FPS: %f", GetTicks(&fps)/1000.f);
SDL_WM_SetCaption(buffer, NULL);

在C中,您可以使用sprintf来完成此操作。

查看此链接:

http://msdn.microsoft.com/en-us/library/ybk95axf (v = vs.71) . aspx

不要使用+来添加char指针(这是C中的char指针,而不是字符串)。

编辑:

如果这是c++,根据编辑,使用std::string,它重载了+操作符。但是,您仍然需要将数字转换为字符串。

也称为串联

您可以使用字符串,或者如果您已经满足于新的当前c++标准,也可以使用std::to_string:

#include <string>
#include <iostream>
int main() {
    const std::string str = "Foobar " + std::to_string(42);
    std::cout << str << 'n';
}
相关文章: