c++ int to string
时间: 2023-12-07 15:35:06 浏览: 126
将 int 类型转换为 string 类型可以使用 C++ 标准库中的 to_string 函数。示例代码如下:
```c++
#include <iostream>
#include <string>
int main() {
int num = 123;
std::string str = std::to_string(num);
std::cout << str << std::endl;
return 0;
}
```
输出结果为:
```
123
```
相关问题
C++ int to string
To convert an integer to a string in C, you can use the sprintf() function. The sprintf() function formats and stores a series of characters and values in a string.
Here's an example:
```c
#include <stdio.h>
int main() {
int num = 123;
char str[20];
sprintf(str, "%d", num);
printf("The integer is: %d\n", num);
printf("The string is: %s\n", str);
return 0;
}
```
Output:
```
The integer is: 123
The string is: 123
```
In the above example, we declared an integer variable "num" and set it to 123. We also declared a character array "str" to store the string version of the integer.
We then used the sprintf() function to convert the integer to a string and store it in the "str" array. The first argument of sprintf() is the buffer to store the string, the second argument is the format string, and the third argument is the integer to be converted.
Finally, we printed both the integer and string versions of the variable to the console.
c++, int to string
在C++中,将整型(int)转换为字符串(string)的一种方法是使用标准库中的`std::to_string`函数。这个函数定义在`<string>`头文件中,从C++11开始提供,可以将基本数据类型的数值转换为字符串。
下面是一个使用`std::to_string`进行转换的简单示例:
```cpp
#include <iostream>
#include <string>
int main() {
int myInt = 123;
std::string myString = std::to_string(myInt);
std::cout << "转换后的字符串是: " << myString << std::endl;
return 0;
}
```
这段代码首先包含了`<iostream>`和`<string>`头文件,然后在`main`函数中创建了一个`int`类型的变量`myInt`并初始化为123,接着使用`std::to_string`函数将`myInt`转换成`std::string`类型的字符串`myString`,最后输出转换后的字符串。
阅读全文