一、c 數字轉字元串列印
c語言中數字轉字元的一種最基本的方式就是使用printf列印函數,通過佔位符輸出數字,將數字自動轉換為對應的字元。例如:
#include<iostream>
using namespace std;
int main() {
int num = 123;
printf("%d\n", num);
return 0;
}
輸出結果為:
123
二、c 數字轉字元串不足兩位補0
在某些場景下,需要將數字轉換為兩位字元,不足兩位的數字需要補0。這時可以使用sprintf函數,其中第一個參數是字元數組,第二個參數是格式化字元串,第三個參數是需要轉換的數字。例如:
#include<iostream>
#include<stdio.h>
using namespace std;
int main() {
int num = 3;
char str[3];
sprintf(str, "%02d", num);
printf("%s\n", str);
return 0;
}
輸出結果為:
03
三、c數字轉字元串輸出的函數
c標準庫中的itoa函數可以實現數字轉字元串的功能。其中第一個參數是需要轉換的數字,第二個參數是存儲轉換結果的字元數組,第三個參數是進位。例如:
#include<iostream>
#include<stdlib.h>
using namespace std;
int main() {
int num = 123;
char str[8];
itoa(num, str, 10);
cout << str << endl;
return 0;
}
輸出結果為:
123
四、c數字轉字元串函數
c++中string庫提供了to_string函數可以實現數字轉字元串的功能。例如:
#include<iostream>
#include<string>
using namespace std;
int main() {
int num = 123;
string str = to_string(num);
cout << str << endl;
return 0;
}
輸出結果為:
123
五、c數字轉字元串 補0
c++11中提供了一個std::setfill函數和std::setw,可以通過setfill設置填充的字元,setw設置保留的位數。例如:
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int num = 3;
cout << std::setfill('0') << std::setw(2) << num << endl;
return 0;
}
輸出結果為:
03
六、c數字轉字元串代碼
c++中數字轉字元串的完整代碼:
#include<iostream>
#include<iomanip>
#include<stdlib.h>
#include<stdio.h>
#include<string>
using namespace std;
int main() {
int num = 123;
char str[8];
// 方法1: printf
printf("%d\n", num);
// 方法2: sprintf, 補0
sprintf(str, "%02d", num);
printf("%s\n", str);
// 方法3: itoa (需要頭文件stdlib.h), 10進位
itoa(num, str, 10);
cout << str << endl;
// 方法4: to_string, c++11
string str2 = to_string(num);
cout << str2 << endl;
// 方法5: 補0, c++11
cout << std::setfill('0') << std::setw(2) << num << endl;
return 0;
}
七、數字轉字元c
c語言中char類型是1個位元組,可以用來存儲字元,但是實際上char類型也可以表示數字。例如:
#include<iostream>
using namespace std;
int main() {
char c = '3';
int num = c - '0';
cout << num << endl;
return 0;
}
輸出結果為:
3
八、sas數字轉字元
SAS語言中也有數字轉字元的功能,它的函數名是put。例如:
data test;
num = 123;
str = put(num, 3.);
put str;
run;
輸出結果為:
123
參考資料:
1. cplusplus.com: sprintf
2. cppreference.com: to_string
3. cplusplus.com: to_string
4. cplusplus.com: std::setw
5. cplusplus.com: std::setfill
6. SAS Help Center: SAS函數
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/236745.html