c++ 字符串和数字转换时的特殊处理

基本用法

表明数字的string如何转化为对应的数字?使用 atoi() 函数。下面是具体写法:ios

#include <iostream>
#include <stdlib.h>  //atoi和atof对应的头文件
#include <string>

using namespace std;

int main(){
    string a = "5";
    cout << atoi(a.c_str()) << endl;

    //输出结果为 5
    return 0;
}

特殊状况

上面的例子只是给出了一个最基本的状况,即咱们须要转化的string是一个整数。函数

通常的,咱们可能会但愿对一些表明浮点数的字符串进行转化,这时能够用和atoi()长得很相似的一个函数atof()spa

这两个函数均可以处理浮点数型的string,然而结果可能不一样,具体结果以下所示。code

#include <iostream>
#include <stdlib.h>
#include <typeinfo>
#include <string>
using namespace std;

int main(){
	string a = "5";
	string b = "5.0";
	string c = "5.5";
	
	cout << atoi(a.c_str()) << endl;
	cout << atoi(b.c_str()) << endl;
	cout << atoi(c.c_str()) << endl;
	cout << atof(a.c_str()) << endl;
	cout << atof(b.c_str()) << endl;
	cout << atof(c.c_str()) << endl;
	
	cout << typeid(atoi(a.c_str())).name() << endl;
	cout << typeid(atoi(b.c_str())).name() << endl;
	cout << typeid(atoi(c.c_str())).name() << endl;
	cout << typeid(atof(a.c_str())).name() << endl;
	cout << typeid(atof(b.c_str())).name() << endl;
	cout << typeid(atof(c.c_str())).name() << endl;
	
	return 0;
}

输出结果以下:blog

能够注意到:字符串

对于atoi()函数来讲,不论输入的string是不是一个浮点数,都会将小数点以后的抹去,输出一个整数;而对于atof()函数来讲,若是是5.0这样的数,也自动会将小数点及后面的0消去。string

尽管你可能会担忧atof()这个自动消去.0的操做会将输出的数字变为一个整型数,然而事实上,经过typeid()查看输出类型可知,atoi()输出的必定是int型的数据,而atof()输出的必定是double型的数据。io

相关文章
相关标签/搜索