在C ++中将int转换为字符串的最简单方法是什么
在本节中,我们将看到如何将整数转换为字符串。
逻辑很简单。在这里,我们将使用该sprintf()方法。此函数用于将某些值或行打印到字符串中,但不在控制台中。这是printf()和之间的唯一区别sprintf()。这里的第一个参数是字符串缓冲区。我们要保存数据的位置。
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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志