Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีง่ายที่สุดในการแปลง int เป็น string ใน C++


ในส่วนนี้ เราจะดูวิธีแปลง integer เป็น string

ตรรกะง่ายมาก ที่นี่เราจะใช้ฟังก์ชัน sprintf() ฟังก์ชันนี้ใช้พิมพ์ค่าหรือบรรทัดเข้าไปใน string แต่ไม่ใช่ในคอนโซล นี่คือความแตกต่างเดียวระหว่าง printf() และ sprintf() ที่นี่ argument แรกคือ string buffer ที่เราต้องการเก็บข้อมูล

Input: User will put some numeric value say 42
Output: This program will return the string equivalent result of that number like "42"

Algorithm

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