#include <stdio.h>
#include<iostream>

#include<string>
using namespace std;
void main()
{
string a;
a="123";
cout<<sizeof(a)<<endl;
int b=0;
b=atoi(a.c_str());
cout<<b<<endl;
}
string的成员a返回的是string类型的对象,而atoi函数要求参数为char*型字符串,所以可以使用string的c_str成员函数,程序必须有.c_str():
b= atoi( a.c_str() );
c_str()函数
const char *c_str();
c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针
比如:最好不要这样:
char* c;
string s="1234";
c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理
应该这样用:
char c[20];
string s="1234";
strcpy(c,s.c_str());
这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作
再举个例子
c_str() 以 char* 形式传回 string 内含字符串
如果一个函数要求char*参数,可以使用c_str()方法:
string s = "Hello World!";
printf("%s", s.c_str()); //输出 "Hello World
atof
函数名: atof
功 能: 把字符串转换成浮点数
用 法: double atof(const char *nptr);
程序例:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
float f;
char *str = "12345.67";
f = atof(str);
printf("string = %s float = %fn", str, f);
return 0;
}
2. atof(将字串转换成浮点型数)
相关函数 atoi,atol,strtod,strtol,strtoul
表头文件 #include <stdlib.h>
定义函数 double atof(const char *nptr);
函数说明 atof()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时(' ')才结束转换,并将结果返回。参数nptr字符串可包含正负号、小数点或E(e)来表示指数部分,如123.456或123e-2。
返回值 返回转换后的浮点型数。
附加说明 atof()与使用strtod(nptr,(char**)NULL)结果相同。
范例 /* 将字符串a 与字符串b转换成数字后相加*/
#include<stdlib.h>
main()
{
char *a=”-100.23”;
char *b=”200e-2”;
float c;
c=atof(a)+atof(b);
printf(“c=%.2fn”,c);
}
执行 c=-98.23
atoi
C语言库函数名: atoi
功 能: 把字符串转换成整型数.
名字来源:array to integer 的缩写.
函数说明: atoi()会扫描参数nptr字符串,如果第一个字符不是数字也不是正负号返回零,否则开始做类型转换,之后检测到非数字或结束符 时停止转换,返回整型数。
原型: int atoi(const char *nptr);
需要用到的头文件: #include <stdlib.h>
程序例:
1)
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int n;
char *str = "12345.67";
n = atoi(str);
printf("string = %s integer = %dn", str, n);
return 0;
}
执行结果
string = 12345.67 integer = 12345
2)
#include <stdlib.h>
#include <stdio.h>
int main()
{
char a[] = "-100" ;
char b[] = "123" ;
int c ;
c = atoi( a ) + atoi( b ) ;
printf("c = %dn", c) ;
return 0;
}
执行结果
c = 23
简单的实现atoi函数的源代码:
int my_atoi(const char *str){
int result = 0;
int signal = 1; /* 默认为正数 */
if((*str>='0'&&*str<='9')||*str=='-'||*str=='+'){
if(*str=='-'||*str=='+'){
if(*str=='-')
signal = -1; /* 输入负数 */
str++;
}
}
else return 0;
/* 开始转换 */
while(*str>='0'&&*str<='9')
result = result*10+(*str++ -'0');
return signal*result;
}