C++ 中怎么把string类型转换为float型或int型? C++处理字符串的方法似乎比较麻烦

如题所述

c++中string是一个定义的类,要将其转换为float 或者 int 应先转为 char* 。
如 string --> int
string str;
int i=atoi(str.c_str());

string -->float
string str;
float f=atof(str.c_str());

其中 c_str() 表示 返回一个c风格的字符串
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-12-08
你可以用char吗??为何非要用string呢!!如果用char就简单多了,可以用C语言的库函数,c++不都兼容吗??
char a[100];
double m;
int n;
n=atoi(a); //转化为整型
m=atof(a); //转化为double型
第2个回答  2010-12-08
#include "stdafx.h"
#include<iomanip>
#include <iostream>
#include <cstdlib>

using namespace std;

int main( )
{
const int slength=20;
char s1[slength]="123";
char s2[slength]="123.4";
char *ps1,*ps2;
ps1=s1;ps2=s2;
cout<<atoi(ps1)<<endl; //转换成int类型
cout<<atof(ps2)<<endl; //转换成float类型

system("pause");
return 0;
}
第3个回答  2010-12-08
int atoi(const char *nptr);