您的位置:首页 > 编程语言 > C语言/C++

几种c/c++中字符串转整形的方法

2014-08-09 16:55 225 查看
转自:/article/8882566.html

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: