▲1、C語(yǔ)言標(biāo)準(zhǔn)庫(kù)函數(shù)atoi()等。
函數(shù)名: atoi
功 能: 把字符串轉(zhuǎn)換成整型數(shù)
用 法: int atoi(const char *nptr);
程序例:
#include <stdlib.h>
int main(void)
{
int n;
char *str = "435";
n = atoi(str);
printf("string = %s integer = %d\n", str, n);
return 0;
}
其他相關(guān)函數(shù)——
函數(shù)名: atof
功 能: 把字符串轉(zhuǎn)換成浮點(diǎn)數(shù)
用 法: double atof(const char *nptr);
程序例:
#include <stdlib.h>
int main(void)
{
float f;
char *str = "12345.67";
f = atof(str);
printf("string = %s float = %f\n", str, f);
return 0;
}
函數(shù)名: atol
功 能: 把字符串轉(zhuǎn)換成長(zhǎng)整型數(shù)
用 法: long atol(const char *nptr);
程序例:
#include <stdlib.h>
int main(void)
{
long l;
char *str = "98765432";
l = atol(lstr);
printf("string = %s integer = %ld\n", str, l);
return(0);
}
▲2、sprintf與Format構(gòu)造字符串——
sprintf和printf都是C的產(chǎn)物,用法幾乎一樣,只是前者打印到字符串,后者直接在命令行上輸出。
int sprintf( char *buffer, const char *format [, argument] … );
除了前兩個(gè)參數(shù)類型固定外,后面可以接任意多個(gè)參數(shù)。而它的精華,顯然就在第二個(gè)參數(shù):格式化字符串(想想printf吧,一樣的)。例:
#include <iostream>
int main()
{
double a(3112);
char s1[10],s2[10];
sprintf(s1,"%d\n",(int)a);
sprintf(s2,"$%.2lf",a);
std::cout<<s1<<s2<<std::endl;
}
在C++里,也可用Format(CString) :
/*VS2005中,項(xiàng)目/屬性/配置屬性里字符集設(shè)置為未配置*/
#include <iostream>
#define _AFXDLL
#include <afx.h>
int main()
{
double a(32);
CString s;
s.Format("$%.2lf",a);
std::cout<<s<<std::endl;
}
▲3、字符串流stringstream提供的轉(zhuǎn)換和/或格式化。
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int num(435);
string s;
ostringstream mystream;
mystream<<num<<"\n";
/*創(chuàng)建一個(gè)名為mystream的ostringstream類型空對(duì)象,
并將指定的內(nèi)容插入該對(duì)象。此時(shí)mystream的內(nèi)容是以下字符:
435\n*/
s=mystream.str();
cout<<s;
}
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string s("435");
int num;
istringstream mystream(s);
mystream>>num;/*num=435*/
cout<<num<<endl;
}
▲4、自己寫函數(shù)。
/*串到數(shù),實(shí)參如("435",&number)*/
void getnumber_from_string(char nums[],int *p)
{
int i,k=strlen(nums);
for(i=0,(*p)=0;i<k;++i)
(*p)+=pow_10(k-i-1)*(*(nums+i)-48);
}
int pow_10(int k) /*10的k次方*/
{
return (k==0?1:10*pow_10(k-1));
}
▲5、想沒(méi)到/~!親想到?jīng)]?望補(bǔ)充>>>>