在 C++ 中将 int 转换为字符串的最简单方法是什么
在本节中,我们将了解如何将整数转换为字符串。
逻辑非常简单。此处,我们将使用 sprintf() 函数。此函数用于将一些值或行打印到字符串中,但不在控制台中。这是它与 printf() 之间的唯一区别。此处,第一个参数是字符串缓冲区。我们需要在此处保存我们的数据。
Input: User will put some numeric value say 42 Output: This program will return the string equivalent result of that number like “42”
算法
Step 1: Take a number from the user Step 2: Create an empty string buffer to store result Step 3: Use sprintf() to convert number to string Step 4: End
示例代码
#include<stdio.h>
main() {
char str[20]; //create an empty string to store number
int number;
printf("Enter a number: ");
scanf("%d", &number);
sprintf(str, "%d", number);//make the number into string using sprintf function
printf("You have entered: %s", str);
}输出
Enter a number: 46 You have entered: 46
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP