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

基本用法

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

#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()

这两个函数都可以处理浮点数型的string,然而结果可能不同,具体结果如下所示。

#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;
}

输出结果如下:

可以注意到:

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

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

posted @ 2020-05-12 23:38  王金翼  阅读(442)  评论(0编辑  收藏  举报