几种c/c++中字符串转整形的方法
2008-12-08 15:39
330 查看
1.自己写一个函数(c/c++)
#include <stdio.h>
#include <assert.h>
/* my string to integer function */
int myfun(char *str){
int i = 0,n = 0,flag = 1;
if(str[0] == '-')
i = 1;flag = -1;
for(; str[i] != '/0' ; i++){
assert(str[i] >= '0' && str[i] <= '9');
n = str[i] - '0' + n*10;
}
return n*flag;
}
int main(int argc, char *argv[])
{
int a;
char str[] = "1024";
a = myfun(str);
printf("%d/n",a);
return 0;
}
2.使用c标准库中的atoi函数(c/c++)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a;double d;
char str[] = "1024";
char strd[] = "3.1415";
a = atoi(str);d =atof(strd);
printf("%d/n",a);
printf("%g/n",d);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
int a;
string str = "1024";
a = atoi(str.c_str());
cout << a <<endl;
return 0;
}
其他相关函数还有atof,atol等。
3.使用sscanf函数(c/c++)
#include <stdio.h>
int main(int argc, char *argv[])
{
int a;double d;
char str[] = "1024";
char strd[] = "3.1415";
sscanf(str,"%d",&a);
sscanf(strd,"%lf",&d);
printf("%d/n",a);
printf("%g/n",d);
return 0;
}
4.使用c标准库中的strtol函数(c/c++)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a,hex_a;double d;
char str[] = "1024";
char hex_str[] = "ff";
char strd[] = "3.1415";
a = strtol(str,NULL,10);hex_a = strtol(hex_str,NULL,16);
d =strtod(strd,NULL);
printf("%d/n",a);
printf("%d/n",hex_a);
printf("%g/n",d);
return 0;
}
其他相关函数还有strtoul,将字符串转换成无符号的长整型数。
5.使用c++中的字符串流istringstream(c++)
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
int a;
string str = "-1024";
istringstream issInt(str);
issInt >> a;
cout << a <<endl;
return 0;
}
不过,GCC(2.95.2)及以前版本并不支持sstream。
6.使用boost库中的lexical_cast函数(c++)
可以到www.boost.org下载最新的boost库,设置IDE的include路径就可以使用大部分boost功能了,具体可以参考http://www.stlchina.org/twiki/bin/view.pl/Main/BoostChina。
#include <boost/lexical_cast.hpp>
#include <iostream>
int main()
{
using boost::lexical_cast;
try{
int a = lexical_cast<int>("1024");
//int a = lexical_cast<int>("xxx"); // exception
double d = lexical_cast<double>("3.14194");
std::cout<<a<<std::endl;
std::cout<<d<<std::endl;
}catch(boost::bad_lexical_cast& e){
std::cout<<e.what()<<std::endl;
}
return 0;
}
相关文章推荐
- 几种c/c++中字符串转整形的方法
- 几种c/c++中字符串转整形的方法
- 几种c/c++中字符串转整形的方法
- 几种c/c++中字符串转整形的方法
- 几种c/c++中字符串转整形的方法
- C++中的几种字符串输入输出方法
- C++中输入字符串的几种方法
- c++怎么读取文件中的中文字符串的几种方法
- C++ 字符串的几种表示方法
- Python-二进制字符串转换为整形的几种方法
- C++ 将数据转为字符串的几种方法
- C++ 将数据转为字符串的几种方法
- 几种C++ 字符串分割的方法
- C/C++整型转字符串的几种方法
- C++:CString、TCHAR、WCHAR 字符串等转BSTR的几种方法。
- C++中输入字符串的几种方法
- C++中字符串的几种表示方法及其深入理解
- C++中输入字符串的几种方法
- 删除字符串最后一个字符的几种方法
- C/C++定义全局变量/常量几种方法的区别