C++ 中字串與數字的相互轉換


在本節中,我們將瞭解如何將字串轉換為數字以及將數字轉換為字串。首先,我們將瞭解如何將字串轉換為數字。

字串到數字的轉換

在這裡,我們將瞭解如何將數字字串轉換為整數型別資料。我們可以使用 atoi() 函式來解決此問題。此函式以字串作為輸入,並將其轉換為整數資料。

atoi() 函式位於 <cstdlib> 庫中。

Input: A number string “1234”
Output: 1234

演算法

Step 1:Take a number string
Step 2: Convert it to integer using atoi() function
Step 3: Print the result.
Step 4: End

示例程式碼

 線上演示

#include<iostream>
#include<cstdlib>
using namespace std;
main() {
   int n;
   char num_string[20] = "1234";
   n = atoi(num_string);
   cout << n;
}

輸出

1234

數字到字串的轉換

在本節中,我們將瞭解如何將數字(整數、浮點數或任何其他數字型別資料)轉換為字串。

邏輯非常簡單。在這裡,我們將使用 sprintf() 函式。此函式用於將某些值或行列印到字串中,而不是在控制檯中列印。這是 printf() 和 sprintf() 之間的唯一區別。這裡第一個引數是字串緩衝區,我們希望將資料儲存到其中。

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

演算法

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
   float number;
   printf("Enter a number: ");
   scanf("%f", &number);
   sprintf(str, "%f", number);//make the number into string using sprintf function
   printf("You have entered: %s", str);
}

輸出

Enter a number: 46.3258
You have entered: 46.325802

更新於: 2019-07-30

656 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.