在 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