C語言中字串與整數的相互轉換
C語言提供了幾個標準庫函式,可以將任意型別(整型、長整型、浮點型等)的數字轉換為字串,下面列舉了各函式的方法及其說明。
# include <stdlib.h>
將數字轉換為字串
● itoa():將整型值轉換為字串。
● ltoa():將長整型值轉換為字串。
● ultoa():將無符號長整型值轉換為字串。
● gcvt():將浮點型數轉換為字串,取四捨五入。
● ecvt():將雙精度浮點型值轉換為字串,轉換結果中不包含十進位制小數點。
● fcvt():指定位數為轉換精度,其餘同ecvt()。
將字串轉換為整數
● atof():將字串轉換為雙精度浮點型值。
● atoi():將字串轉換為整型值。
● atol():將字串轉換為長整型值。
● strtod():將字串轉換為雙精度浮點型值,並報告不能被轉換的所有剩餘數字。
● strtol():將字串轉換為長整值,並報告不能被轉換的所有剩餘數字。
● strtoul():將字串轉換為無符號長整型值,並報告不能被轉換的所有剩餘數字。
千萬不要忘記匯入標頭檔案<stdlib.h>
例:
#include <stdio.h> #include<iostream> #include <string.h> #include<stdlib.h> #include<algorithm> using namespace std; int main(){ char x[1010]; scanf("%s",x); int y=atoi(x); cout<<y; return 0; }
另一種方法:
#include<stdio.h>
從左向右:
#include <stdio.h> #include<iostream> #include <string.h> #include<stdlib.h> #include<algorithm> using namespace std; int main(){ char x[1010]; scanf("%s",x); int y; sscanf(x,"%d",&y);//將字串x以“%d”的方式向寫入到y中; cout<<y; return 0; }
從右向左:
#include <stdio.h>
#include<iostream>
#include <string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int main(){
char x[1010];
int y;
scanf("%d",&y);
sprintf(x,"%d",&y);
cout<<x[0]<<x[2];
return 0;
}
例題 浙江大學PAT
1021. 個位數統計 (15)
時間限制 100 ms記憶體限制 65536 kB
程式碼長度限制 8000 B
判題程式 Standard 作者 CHEN, Yue
給定一個k位整數N = dk-1*10k-1 + ... + d1*101 + d0 (0<=di<=9, i=0,...,k-1, dk-1>0),請編寫程式統計每種不同的個位數字出現的次數。例如:給定N = 100311,則有2個0,3個1,和1個3。
輸入格式:
每個輸入包含1個測試用例,即一個不超過1000位的正整數N。
輸出格式:
對N中每一種不同的個位數字,以D:M的格式在一行中輸出該位數字D及其在N中出現的次數M。要求按D的升序輸出。
輸入樣例:100311輸出樣例:
0:2 1:3 3:1AC程式碼:
#include <stdio.h>
#include<iostream>
#include <string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int main(){
char x[1010];
scanf("%s",x);
int a[10]={0};
int tmp=0;
int l=strlen(x);
for(int i=0;i<=l;i++){
tmp=x[i]-'0';
a[tmp]++;
}
for(int i=0;i<10;i++){
if(a[i]!=0){
cout<<i<<":"<<a[i]<<endl;
}
}
return 0;
}