▲1、C语言标准库函数atoi()等。

函数名: atoi
功 能: 把字符串转换成整型数
用 法: 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;
}

其他相关函数——

函数名: atof
功 能: 把字符串转换成浮点数
用 法: 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;
}

函数名: atol
功 能: 把字符串转换成长整型数
用 法: 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构造字符串——

    sprintf和printf都是C的产物,用法几乎一样,只是前者打印到字符串,后者直接在命令行上输出。
    int sprintf( char *buffer, const char *format [, argument] … );
    除了前两个参数类型固定外,后面可以接任意多个参数。而它的精华,显然就在第二个参数:格式化字符串(想想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中,项目/属性/配置属性里字符集设置为未配置*/
#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提供的转换和/或格式化。

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    int num(435);
    string s;
    ostringstream mystream;
    mystream<<num<<"\n";
    /*创建一个名为mystream的ostringstream类型空对象,
并将指定的内容插入该对象。此时mystream的内容是以下字符:
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、自己写函数。

/*串到数,实参如("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、想没到/~!亲想到没?望补充>>>>

Posted on 2007-07-23 22:50 小王子 阅读(4813) 评论(5)  编辑 收藏 引用 所属分类: 分类1:C++文章

Feedback

# re: ★(原创)C/C++字符串和数字互换方案收集★  回复  更多评论   

2007-07-24 00:34 by 随风而过

# re: ★(原创)C/C++字符串和数字互换方案收集★[未登录]  回复  更多评论   

2007-07-24 08:39 by 漂舟
楼主收集的方法还真不少,
偶补充一个,strtol, strtoul, strtod, 这一系列标准库函数

# re: ★(原创)C/C++字符串和数字互换方案收集★  回复  更多评论   

2007-07-24 09:40 by nickey
boost::lexical_cast

# re: ★(原创)C/C++字符串和数字互换方案收集★  回复  更多评论   

2007-07-24 09:54 by pass86
强烈推荐boost::lexical_cast
SO EASY.

# re: ★(原创)C/C++字符串和数字互换方案收集★[未登录]  回复  更多评论   

2008-09-06 03:25 by Robert
Could you write down:

char* itoa(int n, char* buf)

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理