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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP