如何添加一个数字到一个字符串
How to i add a number to a string?
我想做这样的事情(显示我在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不支持简单类型(如int
或float
)到更复杂类型(如字符串)的转换。
您应该检查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';
}
相关文章:
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 如何检查一个c++字符串中有多少相同的字符/数字
- 获取用C/C++打印的最后一个字符串
- cin >> int 给定一个字符串将 int 赋值为 0
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- C++为 void 指针分配一个字符串
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 如何在另一个字符串的x位置插入一个字符串?
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 在另一个字符串中插入文件扩展名之前的字符串
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- C++自定义流操纵器,用于更改流上的下一个字符串
- 从类返回一个字符串 — 奇怪的行为
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- 你能从"volatile const char*"构造一个字符串吗?(不使用`const_cast`