C/C++字符串和数字互换方案收集★
来源:互联网 发布:域名有 什么作用 编辑:程序博客网 时间:2024/05/20 06:50
▲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));
}
- ★C/C++字符串和数字互换方案收集★
- C/C++字符串和数字互换方案收集★
- C/C++字符串和数字互换方案收集(转)
- C/C++字符串和数字互换方案收集
- C/C++字符串和数字互换方案收集(转)
- C/C++字符串和数字互换方案收集(转)
- Objective-C 中字符串与数字的互换
- 字符串和数字的互换
- 【C++】string类型与数字类型互换
- 使用库函数将字符串和数字互换
- 数字与字符串互换
- C语言 数字和字符串的转换
- c计算数字字符串的和
- c++-字符串和数字互相转换小结
- c字符串转成数字
- 字符串和数字之间的转换(C/C++)
- 字符串和数字之间的转换(C/C++)
- 数字与字符串的互换
- Android选择联系人+返回对应手机号码(转载并加以修正完善)
- ViewPager多页面滑动切换以及动画效果
- Flash Builder快捷键
- android开发中出现的错误集(不断更新)
- New C# Features in the .NET Framework 4
- C/C++字符串和数字互换方案收集★
- 适配器-Adapter
- javascript 小数类型格式化 --oFixed函数
- oracle最大连接数 汇总
- 三种快速排序以及快速排序的优化
- liferay ide 创建主题 Custom Classic Theme with Liferay IDE
- Android之Service案例-电话窃听
- No space left on device的原因
- Android-Sqlite数据库的分页显示。